[英]Saving a bitmap file in android and reading back to display in Imageview
我有一個位圖文件,我需要上傳到我的 php 服務器,但由於文件非常大,我決定調整它的大小並保存它。 稍后我嘗試將其讀回以顯示調整后的圖像。 但是這次我沒有得到相同的圖像下面是編寫圖像和返回文件的代碼
public static File savebitmap(Bitmap bmp) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "testimage.jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
return f;
}
下面是讀取和顯示的代碼
File file=ImageUtil.savebitmap(this.bitmap);
this.imgChoosenImage.setImageURI(Uri.parse(file.getAbsolutePath()));
請告訴我這里到底出了什么問題
首先檢查圖像是否按照定義保存在您的路徑中,並確保您為檢索圖像提供了正確的路徑。 我使用下面的代碼將圖像保存在畫廊中
String iconsStoragePath = Environment.getExternalStorageDirectory()+ File.separator;
File sdIconStorageDir = new File(iconsStoragePath);
//create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
String filePath = null;
filePath = Environment.getExternalStorageDirectory() + File.separator + "testimage" + ".jpg";
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bmp.compress(Bitmap.CompressFormat.JPG, 100, bos);
bos.flush();
bos.close();
} catch (IOException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Failed to Create folder",
Toast.LENGTH_SHORT).show();
}
對於 imageview 中的位圖顯示:
File imgFile = new File("/sdcard/Images/testimage.jpg");
//Here File file = ur file path
if(imgFile.exists())
{
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
權限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.