将位图保存到SdCard Android

时间:2014-06-07 12:33:36

标签: android bitmap png compression

我正在编写一个代码来将png文件转换回bmp并将其保存在SD卡上。这是我目前的代码。

    FileInputStream in;
    BufferedInputStream buf;
    try {
        in = new  FileInputStream("File_Path_to_Read.png");
        buf = new BufferedInputStream(in);
        byte[] bMapArray= new byte[buf.available()];
        buf.read(bMapArray);
        Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);

        //Code segment to save on file
        int numBytesByRow = bMap.getRowBytes() * bMap.getHeight();
        ByteBuffer byteBuffer = ByteBuffer.allocate(numBytesByRow);
        bMap.copyPixelsToBuffer(byteBuffer);
        byte[] bytes = byteBuffer.array();

        FileOutputStream fileOuputStream = new FileOutputStream("File_Path_To_Save.bmp");
        fileOuputStream.write(bytes);
        fileOuputStream.close();


        if (in != null) {
        in.close();
        }
        if (buf != null) {
        buf.close();
        }


    } catch (Exception e) {

    }

我在将bMap保存到Sdcard时遇到问题。我找到的所有例子都使用bMap.compress()。使用这种方法我不能保存为bmp。有人可以举例说明如何在Sdcard上保存位图吗?

编辑: 我现在可以将文件保存为.bmp到sdcard。但是它不会达到原始大小。有关将PNG转换为BMP的任何建议吗?

1 个答案:

答案 0 :(得分:0)

File root = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "My_Folder" + File.separator);
    root.mkdirs();
    File myFile = new File(root, "ABC.jpg");
    Bitmap bitmap = decodeFile(myFile, 800, 600);
    OutputStream out = null;
    File file = new File(mediaStorageDir.getAbsoluteFile() + "/DEF.jpg");
    try {
        out = new FileOutputStream(file);
        bitmap .compress(Bitmap.CompressFormat.JPEG, 80, out);
        out.flush();
        out.close();
        bitmap.recycle();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

public static Bitmap decodeFile(File f, int WIDTH, int HIGHT) {
    try {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f), null, o);

        // The new size we want to scale to
        final int REQUIRED_WIDTH = WIDTH;
        final int REQUIRED_HIGHT = HIGHT;
        // Find the correct scale value. It should be the power of 2.
        int scale = 2;
        while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
                && o.outHeight / scale / 2 >= REQUIRED_HIGHT)
                scale *= 2;

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {
    }
return null;
}
相关问题