在android中保存位图文件并回读以在Imageview中显示

时间:2016-04-22 03:49:18

标签: android bitmap

我有一个位图文件,我需要上传到我的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()));

请告诉我这里到底出了什么问题

1 个答案:

答案 0 :(得分:0)

首先检查图像是否按照定义保存在路径中,并确保为正确的路径提供正确的路径。     我已经使用下面的代码来保存图库中的图像

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" />