我用這個方法將圖像保存到內部存儲(和返回的路徑保存到您的sqlite)使用
private String saveToInternalStorage(Bitmap bitmapImage, String filename){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
Log.d("dir", directory.toString());
// Create imageDir
File mypath=new File(directory,filename);
Log.d("path", mypath.toString());
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.d("ingesteld path", directory.getAbsolutePath());
return directory.getAbsolutePath();
}
加載圖像:
private void loadImageFromStorage(String path, String name)
{
try {
File f=new File(path, name);
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
// Do something with your bitmap
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
希望這是有用的。
謝謝你Opoo。我正在使用ByteArrayOutputStream而不是FileOutputStream來寫入內存。是否可觀?另外,你能幫我理解哪個路徑被存儲到數據庫..是它的路徑 - 「/ data/data/yourapp/app_data/imageDir」? – Kittu
我不知道它是否工作原理相同,在我的情況下,使用上面使用的方法存儲的路徑是「/data/data/com.example.app/app_imageDir」。 String path = saveToInternalStorage(bitmap,name); question.setImagePath(path); – Stefan