Save bitmap to file function












29















I'm trying to save a bitmap to file and a specific directly using a function I've created. It's not working. It crashes after bitmap.compress part (before here3).



    File dir = new File(filepath);

if(!dir.exists())dir.mkdirs();

File file = new File(Environment.getExternalStorageDirectory() + filepath, side + ".png");
FileOutputStream fOut = new FileOutputStream(file);

bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();

System.out.println(filepath);

bitmap.recycle();
System.gc();




Error log:



06-29 00:16:38.089: D/AndroidRuntime(3260): Shutting down VM
06-29 00:16:38.089: W/dalvikvm(3260): threadid=1: thread exiting with uncaught exception (group=0xb587f4f0)
06-29 00:16:38.089: E/AndroidRuntime(3260): FATAL EXCEPTION: main
06-29 00:16:38.089: E/AndroidRuntime(3260): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=android.intent.action.VIEW dat=content://org.openintents.filemanager/mimetype//mnt/sdcard/download/02977_awreckedboatintheocean_1280x1024.jpg }} to activity {com.polygonattraction.testbirds/com.polygonattraction.testbirds.functions.SelectImageSource}: java.lang.IllegalStateException: Can't compress a recycled bitmap
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.deliverResults(ActivityThread.java:2532)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.handleSendResult(ActivityThread.java:2574)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.access$2000(ActivityThread.java:117)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:961)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.os.Handler.dispatchMessage(Handler.java:99)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.os.Looper.loop(Looper.java:130)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-29 00:16:38.089: E/AndroidRuntime(3260): at java.lang.reflect.Method.invokeNative(Native Method)
06-29 00:16:38.089: E/AndroidRuntime(3260): at java.lang.reflect.Method.invoke(Method.java:507)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-29 00:16:38.089: E/AndroidRuntime(3260): at dalvik.system.NativeStart.main(Native Method)
06-29 00:16:38.089: E/AndroidRuntime(3260): Caused by: java.lang.IllegalStateException: Can't compress a recycled bitmap
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.graphics.Bitmap.checkRecycled(Bitmap.java:180)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.graphics.Bitmap.compress(Bitmap.java:581)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.polygonattraction.testbirds.functions.Functions.SaveToFile(Functions.java:144)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.polygonattraction.testbirds.functions.SelectImageSource.onActivityResult(SelectImageSource.java:113)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.Activity.dispatchActivityResult(Activity.java:3908)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.deliverResults(ActivityThread.java:2528)









share|improve this question




















  • 1





    whats your logcat output?

    – Rafael T
    Jun 30 '12 at 14:10











  • "Can't compress a recycled bitmap.".have you called bitmap.recycle(); any where before this ?

    – Dheeresh Singh
    Jun 30 '12 at 15:24













  • I have called it only after it's suppose to have saved it, I've tried removing that but I still get the same error.

    – Oliver Dixon
    Jun 30 '12 at 15:29











  • Side note, if you don't need to collect that bitmap right then and there, you should delay a major collection as long as possible for your apps performance sake, I'd mark everything you need to collect, and then after you've marked everything call for a collection.

    – Trevor Hart
    Sep 27 '17 at 19:47
















29















I'm trying to save a bitmap to file and a specific directly using a function I've created. It's not working. It crashes after bitmap.compress part (before here3).



    File dir = new File(filepath);

if(!dir.exists())dir.mkdirs();

File file = new File(Environment.getExternalStorageDirectory() + filepath, side + ".png");
FileOutputStream fOut = new FileOutputStream(file);

bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();

System.out.println(filepath);

bitmap.recycle();
System.gc();




Error log:



06-29 00:16:38.089: D/AndroidRuntime(3260): Shutting down VM
06-29 00:16:38.089: W/dalvikvm(3260): threadid=1: thread exiting with uncaught exception (group=0xb587f4f0)
06-29 00:16:38.089: E/AndroidRuntime(3260): FATAL EXCEPTION: main
06-29 00:16:38.089: E/AndroidRuntime(3260): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=android.intent.action.VIEW dat=content://org.openintents.filemanager/mimetype//mnt/sdcard/download/02977_awreckedboatintheocean_1280x1024.jpg }} to activity {com.polygonattraction.testbirds/com.polygonattraction.testbirds.functions.SelectImageSource}: java.lang.IllegalStateException: Can't compress a recycled bitmap
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.deliverResults(ActivityThread.java:2532)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.handleSendResult(ActivityThread.java:2574)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.access$2000(ActivityThread.java:117)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:961)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.os.Handler.dispatchMessage(Handler.java:99)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.os.Looper.loop(Looper.java:130)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-29 00:16:38.089: E/AndroidRuntime(3260): at java.lang.reflect.Method.invokeNative(Native Method)
06-29 00:16:38.089: E/AndroidRuntime(3260): at java.lang.reflect.Method.invoke(Method.java:507)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-29 00:16:38.089: E/AndroidRuntime(3260): at dalvik.system.NativeStart.main(Native Method)
06-29 00:16:38.089: E/AndroidRuntime(3260): Caused by: java.lang.IllegalStateException: Can't compress a recycled bitmap
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.graphics.Bitmap.checkRecycled(Bitmap.java:180)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.graphics.Bitmap.compress(Bitmap.java:581)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.polygonattraction.testbirds.functions.Functions.SaveToFile(Functions.java:144)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.polygonattraction.testbirds.functions.SelectImageSource.onActivityResult(SelectImageSource.java:113)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.Activity.dispatchActivityResult(Activity.java:3908)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.deliverResults(ActivityThread.java:2528)









share|improve this question




















  • 1





    whats your logcat output?

    – Rafael T
    Jun 30 '12 at 14:10











  • "Can't compress a recycled bitmap.".have you called bitmap.recycle(); any where before this ?

    – Dheeresh Singh
    Jun 30 '12 at 15:24













  • I have called it only after it's suppose to have saved it, I've tried removing that but I still get the same error.

    – Oliver Dixon
    Jun 30 '12 at 15:29











  • Side note, if you don't need to collect that bitmap right then and there, you should delay a major collection as long as possible for your apps performance sake, I'd mark everything you need to collect, and then after you've marked everything call for a collection.

    – Trevor Hart
    Sep 27 '17 at 19:47














29












29








29


6






I'm trying to save a bitmap to file and a specific directly using a function I've created. It's not working. It crashes after bitmap.compress part (before here3).



    File dir = new File(filepath);

if(!dir.exists())dir.mkdirs();

File file = new File(Environment.getExternalStorageDirectory() + filepath, side + ".png");
FileOutputStream fOut = new FileOutputStream(file);

bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();

System.out.println(filepath);

bitmap.recycle();
System.gc();




Error log:



06-29 00:16:38.089: D/AndroidRuntime(3260): Shutting down VM
06-29 00:16:38.089: W/dalvikvm(3260): threadid=1: thread exiting with uncaught exception (group=0xb587f4f0)
06-29 00:16:38.089: E/AndroidRuntime(3260): FATAL EXCEPTION: main
06-29 00:16:38.089: E/AndroidRuntime(3260): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=android.intent.action.VIEW dat=content://org.openintents.filemanager/mimetype//mnt/sdcard/download/02977_awreckedboatintheocean_1280x1024.jpg }} to activity {com.polygonattraction.testbirds/com.polygonattraction.testbirds.functions.SelectImageSource}: java.lang.IllegalStateException: Can't compress a recycled bitmap
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.deliverResults(ActivityThread.java:2532)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.handleSendResult(ActivityThread.java:2574)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.access$2000(ActivityThread.java:117)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:961)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.os.Handler.dispatchMessage(Handler.java:99)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.os.Looper.loop(Looper.java:130)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-29 00:16:38.089: E/AndroidRuntime(3260): at java.lang.reflect.Method.invokeNative(Native Method)
06-29 00:16:38.089: E/AndroidRuntime(3260): at java.lang.reflect.Method.invoke(Method.java:507)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-29 00:16:38.089: E/AndroidRuntime(3260): at dalvik.system.NativeStart.main(Native Method)
06-29 00:16:38.089: E/AndroidRuntime(3260): Caused by: java.lang.IllegalStateException: Can't compress a recycled bitmap
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.graphics.Bitmap.checkRecycled(Bitmap.java:180)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.graphics.Bitmap.compress(Bitmap.java:581)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.polygonattraction.testbirds.functions.Functions.SaveToFile(Functions.java:144)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.polygonattraction.testbirds.functions.SelectImageSource.onActivityResult(SelectImageSource.java:113)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.Activity.dispatchActivityResult(Activity.java:3908)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.deliverResults(ActivityThread.java:2528)









share|improve this question
















I'm trying to save a bitmap to file and a specific directly using a function I've created. It's not working. It crashes after bitmap.compress part (before here3).



    File dir = new File(filepath);

if(!dir.exists())dir.mkdirs();

File file = new File(Environment.getExternalStorageDirectory() + filepath, side + ".png");
FileOutputStream fOut = new FileOutputStream(file);

bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();

System.out.println(filepath);

bitmap.recycle();
System.gc();




Error log:



06-29 00:16:38.089: D/AndroidRuntime(3260): Shutting down VM
06-29 00:16:38.089: W/dalvikvm(3260): threadid=1: thread exiting with uncaught exception (group=0xb587f4f0)
06-29 00:16:38.089: E/AndroidRuntime(3260): FATAL EXCEPTION: main
06-29 00:16:38.089: E/AndroidRuntime(3260): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=android.intent.action.VIEW dat=content://org.openintents.filemanager/mimetype//mnt/sdcard/download/02977_awreckedboatintheocean_1280x1024.jpg }} to activity {com.polygonattraction.testbirds/com.polygonattraction.testbirds.functions.SelectImageSource}: java.lang.IllegalStateException: Can't compress a recycled bitmap
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.deliverResults(ActivityThread.java:2532)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.handleSendResult(ActivityThread.java:2574)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.access$2000(ActivityThread.java:117)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:961)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.os.Handler.dispatchMessage(Handler.java:99)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.os.Looper.loop(Looper.java:130)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-29 00:16:38.089: E/AndroidRuntime(3260): at java.lang.reflect.Method.invokeNative(Native Method)
06-29 00:16:38.089: E/AndroidRuntime(3260): at java.lang.reflect.Method.invoke(Method.java:507)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-29 00:16:38.089: E/AndroidRuntime(3260): at dalvik.system.NativeStart.main(Native Method)
06-29 00:16:38.089: E/AndroidRuntime(3260): Caused by: java.lang.IllegalStateException: Can't compress a recycled bitmap
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.graphics.Bitmap.checkRecycled(Bitmap.java:180)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.graphics.Bitmap.compress(Bitmap.java:581)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.polygonattraction.testbirds.functions.Functions.SaveToFile(Functions.java:144)
06-29 00:16:38.089: E/AndroidRuntime(3260): at com.polygonattraction.testbirds.functions.SelectImageSource.onActivityResult(SelectImageSource.java:113)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.Activity.dispatchActivityResult(Activity.java:3908)
06-29 00:16:38.089: E/AndroidRuntime(3260): at android.app.ActivityThread.deliverResults(ActivityThread.java:2528)






android file-io android-intent bitmap android-file






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 30 '12 at 15:22









Dheeresh Singh

14.4k33132




14.4k33132










asked Jun 30 '12 at 14:09









Oliver DixonOliver Dixon

3,80053861




3,80053861








  • 1





    whats your logcat output?

    – Rafael T
    Jun 30 '12 at 14:10











  • "Can't compress a recycled bitmap.".have you called bitmap.recycle(); any where before this ?

    – Dheeresh Singh
    Jun 30 '12 at 15:24













  • I have called it only after it's suppose to have saved it, I've tried removing that but I still get the same error.

    – Oliver Dixon
    Jun 30 '12 at 15:29











  • Side note, if you don't need to collect that bitmap right then and there, you should delay a major collection as long as possible for your apps performance sake, I'd mark everything you need to collect, and then after you've marked everything call for a collection.

    – Trevor Hart
    Sep 27 '17 at 19:47














  • 1





    whats your logcat output?

    – Rafael T
    Jun 30 '12 at 14:10











  • "Can't compress a recycled bitmap.".have you called bitmap.recycle(); any where before this ?

    – Dheeresh Singh
    Jun 30 '12 at 15:24













  • I have called it only after it's suppose to have saved it, I've tried removing that but I still get the same error.

    – Oliver Dixon
    Jun 30 '12 at 15:29











  • Side note, if you don't need to collect that bitmap right then and there, you should delay a major collection as long as possible for your apps performance sake, I'd mark everything you need to collect, and then after you've marked everything call for a collection.

    – Trevor Hart
    Sep 27 '17 at 19:47








1




1





whats your logcat output?

– Rafael T
Jun 30 '12 at 14:10





whats your logcat output?

– Rafael T
Jun 30 '12 at 14:10













"Can't compress a recycled bitmap.".have you called bitmap.recycle(); any where before this ?

– Dheeresh Singh
Jun 30 '12 at 15:24







"Can't compress a recycled bitmap.".have you called bitmap.recycle(); any where before this ?

– Dheeresh Singh
Jun 30 '12 at 15:24















I have called it only after it's suppose to have saved it, I've tried removing that but I still get the same error.

– Oliver Dixon
Jun 30 '12 at 15:29





I have called it only after it's suppose to have saved it, I've tried removing that but I still get the same error.

– Oliver Dixon
Jun 30 '12 at 15:29













Side note, if you don't need to collect that bitmap right then and there, you should delay a major collection as long as possible for your apps performance sake, I'd mark everything you need to collect, and then after you've marked everything call for a collection.

– Trevor Hart
Sep 27 '17 at 19:47





Side note, if you don't need to collect that bitmap right then and there, you should delay a major collection as long as possible for your apps performance sake, I'd mark everything you need to collect, and then after you've marked everything call for a collection.

– Trevor Hart
Sep 27 '17 at 19:47












5 Answers
5






active

oldest

votes


















71
















  1. You need an appropriate permission in manifest.xml:



    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


  2. out.flush() check the out is not null..


  3. String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
    "/PhysicsSketchpad";
    File dir = new File(file_path);
    if(!dir.exists())
    dir.mkdirs();
    File file = new File(dir, "sketchpad" + pad.t_id + ".png");
    FileOutputStream fOut = new FileOutputStream(file);

    bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();






share|improve this answer


























  • yes............

    – Dheeresh Singh
    Jun 30 '12 at 15:01











  • sorry not get , are you want to write file if it not exists only ?

    – Dheeresh Singh
    Jun 30 '12 at 15:09











  • "it crashes" Please provide the log cat of crash...

    – Dheeresh Singh
    Jun 30 '12 at 15:11











  • Need add try - catch. and how it works

    – user1755546
    Dec 19 '12 at 11:18











  • compress rate 85 will be skipped for PNG, as for the JPEG - 90 is optimal.

    – Kirill Karmazin
    Oct 27 '18 at 18:22



















14














I think this is much better answer.



two example works for me, for your reference.



Bitmap bitmap = Utils.decodeBase64(base64);
try{
File file = new File(filePath);
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();}
catch (Exception e) {
e.printStackTrace();
LOG.i(null, "Save file error!");
return false;
}


and this one



    Bitmap savePic = Utils.decodeBase64(base64);
File file = new File(filePath);
File path = new File(file.getParent());

if (savePic != null) {
try {
// build directory
if (file.getParent() != null && !path.isDirectory()) {
path.mkdirs();
}
// output image to file
FileOutputStream fos = new FileOutputStream(filePath);
savePic.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
ret = true;
} catch (Exception e) {
e.printStackTrace();
}

} else {
LOG.i(TAG, "savePicture image parsing error");
}


I think this is much better answer.






share|improve this answer

































    5














    Here is the function which help you



    private void saveBitmap(Bitmap bitmap,String path){
    if(bitmap!=null){
    try {
    FileOutputStream outputStream = null;
    try {
    outputStream = new FileOutputStream(path); //here is set your file path where you want to save or also here you can set file object directly

    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
    // PNG is a lossless format, the compression factor (100) is ignored
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    if (outputStream != null) {
    outputStream.close();
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }





    share|improve this answer































      1














      In kotlin :



      private fun File.writeBitmap(bitmap: Bitmap, format: Bitmap.CompressFormat, quality: Int) {
      outputStream().use{ out->
      bitmap.compress(format, quality, out)
      out.flush()
      }
      }


      usage example:



      File(exportDir, "map.png").writeBitmap(bitmap, Bitmap.CompressFormat.PNG, 85)





      share|improve this answer

































        -3














        implementation save bitmap and load bitmap directly. fast and ease on mfc class



        void CMRSMATH1Dlg::Loadit(TCHAR *destination, CDC &memdc)
        {
        CImage img;
        PBITMAPINFO bmi;
        BITMAPINFOHEADER Info;
        BITMAPFILEHEADER bFileHeader;
        CBitmap bm;
        CFile file2;
        file2.Open(destination, CFile::modeRead | CFile::typeBinary);
        file2.Read(&bFileHeader, sizeof(BITMAPFILEHEADER));
        file2.Read(&Info, sizeof(BITMAPINFOHEADER));
        BYTE ch;
        int width = Info.biWidth;
        int height = Info.biHeight;
        if (height < 0)height = -height;
        int size1 = width*height * 3;
        int size2 = ((width * 24 + 31) / 32) * 4 * height;
        int widthnew = (size2 - size1) / height;
        BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);
        //////////////////////////
        HGDIOBJ old;
        unsigned char alpha = 0;
        int z = 0;
        z = 0;
        int gap = (size2 - size1) / height;
        for (int y = 0;y < height;y++)
        {
        for (int x = 0;x < width*3;x++)
        {
        file2.Read(&ch, 1);
        buffer[z] = ch;
        z++;
        }
        for (int z1 = 0;z1 <gap;z1++)
        {
        file2.Read(&ch,1);
        }
        }
        bm.CreateCompatibleBitmap(&memdc, width, height);
        bm.SetBitmapBits(size1,buffer);
        old = memdc.SelectObject(&bm);
        ///////////////////////////
        //bm.SetBitmapBits(size1, buffer);
        GetDC()->BitBlt(1, 95, width, height, &memdc, 0, 0, SRCCOPY);
        memdc.SelectObject(&old);
        bm.DeleteObject();
        GlobalFree(buffer);
        file2.Close();
        }
        void CMRSMATH1Dlg::saveit(CBitmap &bit1, CDC &memdc, TCHAR *destination)
        {
        BITMAP bm;
        PBITMAPINFO bmi;
        BITMAPINFOHEADER Info;
        BITMAPFILEHEADER bFileHeader;
        CFile file1;
        CSize size = bit1.GetBitmap(&bm);
        int z = 0;
        BYTE ch = 0;
        size.cx = bm.bmWidth;
        size.cy = bm.bmHeight;
        int width = size.cx;
        int size1 = (size.cx)*(size.cy);
        int size2 = size1 * 3;
        size1 = ((size.cx * 24 + 31) / 32) *4* size.cy;
        BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);
        bFileHeader.bfType = 'B' + ('M' << 8);
        bFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
        bFileHeader.bfSize = bFileHeader.bfOffBits + size1;
        bFileHeader.bfReserved1 = 0;
        bFileHeader.bfReserved2 = 0;
        Info.biSize = sizeof(BITMAPINFOHEADER);
        Info.biPlanes = 1;
        Info.biBitCount = 24;//bm.bmBitsPixel;//bitsperpixel///////////////////32
        Info.biCompression = BI_RGB;
        Info.biWidth =bm.bmWidth;
        Info.biHeight =-bm.bmHeight;///reverse pic if negative height
        Info.biSizeImage =size1;
        Info.biClrImportant = 0;
        if (bm.bmBitsPixel <= 8)
        {
        Info.biClrUsed = 1 << bm.bmBitsPixel;
        }else
        Info.biClrUsed = 0;
        Info.biXPelsPerMeter = 0;
        Info.biYPelsPerMeter = 0;
        bit1.GetBitmapBits(size2, buffer);
        file1.Open(destination, CFile::modeCreate | CFile::modeWrite |CFile::typeBinary,0);
        file1.Write(&bFileHeader, sizeof(BITMAPFILEHEADER));
        file1.Write(&Info, sizeof(BITMAPINFOHEADER));
        unsigned char alpha = 0;
        for (int y = 0;y<size.cy;y++)
        {
        for (int x = 0;x<size.cx;x++)
        {
        //for reverse picture below
        //z = (((size.cy - 1 - y)*size.cx) + (x)) * 3;
        z = (((y)*size.cx) + (x)) * 3;
        file1.Write(&buffer[z], 1);
        file1.Write(&buffer[z + 1], 1);
        file1.Write(&buffer[z + 2], 1);
        }
        for (int z = 0;z < (size1 - size2) / size.cy;z++)
        {
        file1.Write(&alpha, 1);
        }
        }
        GlobalFree(buffer);
        file1.Close();
        file1.m_hFile = NULL;
        }





        share|improve this answer



















        • 1





          Please note the android tag in the question

          – laalto
          Jul 5 '18 at 7:49











        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11274715%2fsave-bitmap-to-file-function%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        5 Answers
        5






        active

        oldest

        votes








        5 Answers
        5






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        71
















        1. You need an appropriate permission in manifest.xml:



          <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


        2. out.flush() check the out is not null..


        3. String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
          "/PhysicsSketchpad";
          File dir = new File(file_path);
          if(!dir.exists())
          dir.mkdirs();
          File file = new File(dir, "sketchpad" + pad.t_id + ".png");
          FileOutputStream fOut = new FileOutputStream(file);

          bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
          fOut.flush();
          fOut.close();






        share|improve this answer


























        • yes............

          – Dheeresh Singh
          Jun 30 '12 at 15:01











        • sorry not get , are you want to write file if it not exists only ?

          – Dheeresh Singh
          Jun 30 '12 at 15:09











        • "it crashes" Please provide the log cat of crash...

          – Dheeresh Singh
          Jun 30 '12 at 15:11











        • Need add try - catch. and how it works

          – user1755546
          Dec 19 '12 at 11:18











        • compress rate 85 will be skipped for PNG, as for the JPEG - 90 is optimal.

          – Kirill Karmazin
          Oct 27 '18 at 18:22
















        71
















        1. You need an appropriate permission in manifest.xml:



          <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


        2. out.flush() check the out is not null..


        3. String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
          "/PhysicsSketchpad";
          File dir = new File(file_path);
          if(!dir.exists())
          dir.mkdirs();
          File file = new File(dir, "sketchpad" + pad.t_id + ".png");
          FileOutputStream fOut = new FileOutputStream(file);

          bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
          fOut.flush();
          fOut.close();






        share|improve this answer


























        • yes............

          – Dheeresh Singh
          Jun 30 '12 at 15:01











        • sorry not get , are you want to write file if it not exists only ?

          – Dheeresh Singh
          Jun 30 '12 at 15:09











        • "it crashes" Please provide the log cat of crash...

          – Dheeresh Singh
          Jun 30 '12 at 15:11











        • Need add try - catch. and how it works

          – user1755546
          Dec 19 '12 at 11:18











        • compress rate 85 will be skipped for PNG, as for the JPEG - 90 is optimal.

          – Kirill Karmazin
          Oct 27 '18 at 18:22














        71












        71








        71









        1. You need an appropriate permission in manifest.xml:



          <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


        2. out.flush() check the out is not null..


        3. String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
          "/PhysicsSketchpad";
          File dir = new File(file_path);
          if(!dir.exists())
          dir.mkdirs();
          File file = new File(dir, "sketchpad" + pad.t_id + ".png");
          FileOutputStream fOut = new FileOutputStream(file);

          bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
          fOut.flush();
          fOut.close();






        share|improve this answer

















        1. You need an appropriate permission in manifest.xml:



          <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


        2. out.flush() check the out is not null..


        3. String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
          "/PhysicsSketchpad";
          File dir = new File(file_path);
          if(!dir.exists())
          dir.mkdirs();
          File file = new File(dir, "sketchpad" + pad.t_id + ".png");
          FileOutputStream fOut = new FileOutputStream(file);

          bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
          fOut.flush();
          fOut.close();







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Apr 10 '17 at 15:14









        Floern

        27k1582101




        27k1582101










        answered Jun 30 '12 at 14:22









        Dheeresh SinghDheeresh Singh

        14.4k33132




        14.4k33132













        • yes............

          – Dheeresh Singh
          Jun 30 '12 at 15:01











        • sorry not get , are you want to write file if it not exists only ?

          – Dheeresh Singh
          Jun 30 '12 at 15:09











        • "it crashes" Please provide the log cat of crash...

          – Dheeresh Singh
          Jun 30 '12 at 15:11











        • Need add try - catch. and how it works

          – user1755546
          Dec 19 '12 at 11:18











        • compress rate 85 will be skipped for PNG, as for the JPEG - 90 is optimal.

          – Kirill Karmazin
          Oct 27 '18 at 18:22



















        • yes............

          – Dheeresh Singh
          Jun 30 '12 at 15:01











        • sorry not get , are you want to write file if it not exists only ?

          – Dheeresh Singh
          Jun 30 '12 at 15:09











        • "it crashes" Please provide the log cat of crash...

          – Dheeresh Singh
          Jun 30 '12 at 15:11











        • Need add try - catch. and how it works

          – user1755546
          Dec 19 '12 at 11:18











        • compress rate 85 will be skipped for PNG, as for the JPEG - 90 is optimal.

          – Kirill Karmazin
          Oct 27 '18 at 18:22

















        yes............

        – Dheeresh Singh
        Jun 30 '12 at 15:01





        yes............

        – Dheeresh Singh
        Jun 30 '12 at 15:01













        sorry not get , are you want to write file if it not exists only ?

        – Dheeresh Singh
        Jun 30 '12 at 15:09





        sorry not get , are you want to write file if it not exists only ?

        – Dheeresh Singh
        Jun 30 '12 at 15:09













        "it crashes" Please provide the log cat of crash...

        – Dheeresh Singh
        Jun 30 '12 at 15:11





        "it crashes" Please provide the log cat of crash...

        – Dheeresh Singh
        Jun 30 '12 at 15:11













        Need add try - catch. and how it works

        – user1755546
        Dec 19 '12 at 11:18





        Need add try - catch. and how it works

        – user1755546
        Dec 19 '12 at 11:18













        compress rate 85 will be skipped for PNG, as for the JPEG - 90 is optimal.

        – Kirill Karmazin
        Oct 27 '18 at 18:22





        compress rate 85 will be skipped for PNG, as for the JPEG - 90 is optimal.

        – Kirill Karmazin
        Oct 27 '18 at 18:22













        14














        I think this is much better answer.



        two example works for me, for your reference.



        Bitmap bitmap = Utils.decodeBase64(base64);
        try{
        File file = new File(filePath);
        FileOutputStream fOut = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
        fOut.flush();
        fOut.close();}
        catch (Exception e) {
        e.printStackTrace();
        LOG.i(null, "Save file error!");
        return false;
        }


        and this one



            Bitmap savePic = Utils.decodeBase64(base64);
        File file = new File(filePath);
        File path = new File(file.getParent());

        if (savePic != null) {
        try {
        // build directory
        if (file.getParent() != null && !path.isDirectory()) {
        path.mkdirs();
        }
        // output image to file
        FileOutputStream fos = new FileOutputStream(filePath);
        savePic.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
        ret = true;
        } catch (Exception e) {
        e.printStackTrace();
        }

        } else {
        LOG.i(TAG, "savePicture image parsing error");
        }


        I think this is much better answer.






        share|improve this answer






























          14














          I think this is much better answer.



          two example works for me, for your reference.



          Bitmap bitmap = Utils.decodeBase64(base64);
          try{
          File file = new File(filePath);
          FileOutputStream fOut = new FileOutputStream(file);
          bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
          fOut.flush();
          fOut.close();}
          catch (Exception e) {
          e.printStackTrace();
          LOG.i(null, "Save file error!");
          return false;
          }


          and this one



              Bitmap savePic = Utils.decodeBase64(base64);
          File file = new File(filePath);
          File path = new File(file.getParent());

          if (savePic != null) {
          try {
          // build directory
          if (file.getParent() != null && !path.isDirectory()) {
          path.mkdirs();
          }
          // output image to file
          FileOutputStream fos = new FileOutputStream(filePath);
          savePic.compress(Bitmap.CompressFormat.PNG, 90, fos);
          fos.close();
          ret = true;
          } catch (Exception e) {
          e.printStackTrace();
          }

          } else {
          LOG.i(TAG, "savePicture image parsing error");
          }


          I think this is much better answer.






          share|improve this answer




























            14












            14








            14







            I think this is much better answer.



            two example works for me, for your reference.



            Bitmap bitmap = Utils.decodeBase64(base64);
            try{
            File file = new File(filePath);
            FileOutputStream fOut = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
            fOut.flush();
            fOut.close();}
            catch (Exception e) {
            e.printStackTrace();
            LOG.i(null, "Save file error!");
            return false;
            }


            and this one



                Bitmap savePic = Utils.decodeBase64(base64);
            File file = new File(filePath);
            File path = new File(file.getParent());

            if (savePic != null) {
            try {
            // build directory
            if (file.getParent() != null && !path.isDirectory()) {
            path.mkdirs();
            }
            // output image to file
            FileOutputStream fos = new FileOutputStream(filePath);
            savePic.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.close();
            ret = true;
            } catch (Exception e) {
            e.printStackTrace();
            }

            } else {
            LOG.i(TAG, "savePicture image parsing error");
            }


            I think this is much better answer.






            share|improve this answer















            I think this is much better answer.



            two example works for me, for your reference.



            Bitmap bitmap = Utils.decodeBase64(base64);
            try{
            File file = new File(filePath);
            FileOutputStream fOut = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
            fOut.flush();
            fOut.close();}
            catch (Exception e) {
            e.printStackTrace();
            LOG.i(null, "Save file error!");
            return false;
            }


            and this one



                Bitmap savePic = Utils.decodeBase64(base64);
            File file = new File(filePath);
            File path = new File(file.getParent());

            if (savePic != null) {
            try {
            // build directory
            if (file.getParent() != null && !path.isDirectory()) {
            path.mkdirs();
            }
            // output image to file
            FileOutputStream fos = new FileOutputStream(filePath);
            savePic.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.close();
            ret = true;
            } catch (Exception e) {
            e.printStackTrace();
            }

            } else {
            LOG.i(TAG, "savePicture image parsing error");
            }


            I think this is much better answer.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 26 '16 at 8:23

























            answered Jun 11 '13 at 1:48









            DevonDevon

            1,83021622




            1,83021622























                5














                Here is the function which help you



                private void saveBitmap(Bitmap bitmap,String path){
                if(bitmap!=null){
                try {
                FileOutputStream outputStream = null;
                try {
                outputStream = new FileOutputStream(path); //here is set your file path where you want to save or also here you can set file object directly

                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
                // PNG is a lossless format, the compression factor (100) is ignored
                } catch (Exception e) {
                e.printStackTrace();
                } finally {
                try {
                if (outputStream != null) {
                outputStream.close();
                }
                } catch (IOException e) {
                e.printStackTrace();
                }
                }
                } catch (Exception e) {
                e.printStackTrace();
                }
                }
                }





                share|improve this answer




























                  5














                  Here is the function which help you



                  private void saveBitmap(Bitmap bitmap,String path){
                  if(bitmap!=null){
                  try {
                  FileOutputStream outputStream = null;
                  try {
                  outputStream = new FileOutputStream(path); //here is set your file path where you want to save or also here you can set file object directly

                  bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
                  // PNG is a lossless format, the compression factor (100) is ignored
                  } catch (Exception e) {
                  e.printStackTrace();
                  } finally {
                  try {
                  if (outputStream != null) {
                  outputStream.close();
                  }
                  } catch (IOException e) {
                  e.printStackTrace();
                  }
                  }
                  } catch (Exception e) {
                  e.printStackTrace();
                  }
                  }
                  }





                  share|improve this answer


























                    5












                    5








                    5







                    Here is the function which help you



                    private void saveBitmap(Bitmap bitmap,String path){
                    if(bitmap!=null){
                    try {
                    FileOutputStream outputStream = null;
                    try {
                    outputStream = new FileOutputStream(path); //here is set your file path where you want to save or also here you can set file object directly

                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
                    // PNG is a lossless format, the compression factor (100) is ignored
                    } catch (Exception e) {
                    e.printStackTrace();
                    } finally {
                    try {
                    if (outputStream != null) {
                    outputStream.close();
                    }
                    } catch (IOException e) {
                    e.printStackTrace();
                    }
                    }
                    } catch (Exception e) {
                    e.printStackTrace();
                    }
                    }
                    }





                    share|improve this answer













                    Here is the function which help you



                    private void saveBitmap(Bitmap bitmap,String path){
                    if(bitmap!=null){
                    try {
                    FileOutputStream outputStream = null;
                    try {
                    outputStream = new FileOutputStream(path); //here is set your file path where you want to save or also here you can set file object directly

                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
                    // PNG is a lossless format, the compression factor (100) is ignored
                    } catch (Exception e) {
                    e.printStackTrace();
                    } finally {
                    try {
                    if (outputStream != null) {
                    outputStream.close();
                    }
                    } catch (IOException e) {
                    e.printStackTrace();
                    }
                    }
                    } catch (Exception e) {
                    e.printStackTrace();
                    }
                    }
                    }






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Aug 24 '16 at 7:06









                    Dhaval SolankiDhaval Solanki

                    2,70211324




                    2,70211324























                        1














                        In kotlin :



                        private fun File.writeBitmap(bitmap: Bitmap, format: Bitmap.CompressFormat, quality: Int) {
                        outputStream().use{ out->
                        bitmap.compress(format, quality, out)
                        out.flush()
                        }
                        }


                        usage example:



                        File(exportDir, "map.png").writeBitmap(bitmap, Bitmap.CompressFormat.PNG, 85)





                        share|improve this answer






























                          1














                          In kotlin :



                          private fun File.writeBitmap(bitmap: Bitmap, format: Bitmap.CompressFormat, quality: Int) {
                          outputStream().use{ out->
                          bitmap.compress(format, quality, out)
                          out.flush()
                          }
                          }


                          usage example:



                          File(exportDir, "map.png").writeBitmap(bitmap, Bitmap.CompressFormat.PNG, 85)





                          share|improve this answer




























                            1












                            1








                            1







                            In kotlin :



                            private fun File.writeBitmap(bitmap: Bitmap, format: Bitmap.CompressFormat, quality: Int) {
                            outputStream().use{ out->
                            bitmap.compress(format, quality, out)
                            out.flush()
                            }
                            }


                            usage example:



                            File(exportDir, "map.png").writeBitmap(bitmap, Bitmap.CompressFormat.PNG, 85)





                            share|improve this answer















                            In kotlin :



                            private fun File.writeBitmap(bitmap: Bitmap, format: Bitmap.CompressFormat, quality: Int) {
                            outputStream().use{ out->
                            bitmap.compress(format, quality, out)
                            out.flush()
                            }
                            }


                            usage example:



                            File(exportDir, "map.png").writeBitmap(bitmap, Bitmap.CompressFormat.PNG, 85)






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 21 '18 at 3:42









                            Tadaboody

                            19827




                            19827










                            answered Aug 25 '18 at 17:44









                            RenetikRenetik

                            1,9812235




                            1,9812235























                                -3














                                implementation save bitmap and load bitmap directly. fast and ease on mfc class



                                void CMRSMATH1Dlg::Loadit(TCHAR *destination, CDC &memdc)
                                {
                                CImage img;
                                PBITMAPINFO bmi;
                                BITMAPINFOHEADER Info;
                                BITMAPFILEHEADER bFileHeader;
                                CBitmap bm;
                                CFile file2;
                                file2.Open(destination, CFile::modeRead | CFile::typeBinary);
                                file2.Read(&bFileHeader, sizeof(BITMAPFILEHEADER));
                                file2.Read(&Info, sizeof(BITMAPINFOHEADER));
                                BYTE ch;
                                int width = Info.biWidth;
                                int height = Info.biHeight;
                                if (height < 0)height = -height;
                                int size1 = width*height * 3;
                                int size2 = ((width * 24 + 31) / 32) * 4 * height;
                                int widthnew = (size2 - size1) / height;
                                BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);
                                //////////////////////////
                                HGDIOBJ old;
                                unsigned char alpha = 0;
                                int z = 0;
                                z = 0;
                                int gap = (size2 - size1) / height;
                                for (int y = 0;y < height;y++)
                                {
                                for (int x = 0;x < width*3;x++)
                                {
                                file2.Read(&ch, 1);
                                buffer[z] = ch;
                                z++;
                                }
                                for (int z1 = 0;z1 <gap;z1++)
                                {
                                file2.Read(&ch,1);
                                }
                                }
                                bm.CreateCompatibleBitmap(&memdc, width, height);
                                bm.SetBitmapBits(size1,buffer);
                                old = memdc.SelectObject(&bm);
                                ///////////////////////////
                                //bm.SetBitmapBits(size1, buffer);
                                GetDC()->BitBlt(1, 95, width, height, &memdc, 0, 0, SRCCOPY);
                                memdc.SelectObject(&old);
                                bm.DeleteObject();
                                GlobalFree(buffer);
                                file2.Close();
                                }
                                void CMRSMATH1Dlg::saveit(CBitmap &bit1, CDC &memdc, TCHAR *destination)
                                {
                                BITMAP bm;
                                PBITMAPINFO bmi;
                                BITMAPINFOHEADER Info;
                                BITMAPFILEHEADER bFileHeader;
                                CFile file1;
                                CSize size = bit1.GetBitmap(&bm);
                                int z = 0;
                                BYTE ch = 0;
                                size.cx = bm.bmWidth;
                                size.cy = bm.bmHeight;
                                int width = size.cx;
                                int size1 = (size.cx)*(size.cy);
                                int size2 = size1 * 3;
                                size1 = ((size.cx * 24 + 31) / 32) *4* size.cy;
                                BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);
                                bFileHeader.bfType = 'B' + ('M' << 8);
                                bFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
                                bFileHeader.bfSize = bFileHeader.bfOffBits + size1;
                                bFileHeader.bfReserved1 = 0;
                                bFileHeader.bfReserved2 = 0;
                                Info.biSize = sizeof(BITMAPINFOHEADER);
                                Info.biPlanes = 1;
                                Info.biBitCount = 24;//bm.bmBitsPixel;//bitsperpixel///////////////////32
                                Info.biCompression = BI_RGB;
                                Info.biWidth =bm.bmWidth;
                                Info.biHeight =-bm.bmHeight;///reverse pic if negative height
                                Info.biSizeImage =size1;
                                Info.biClrImportant = 0;
                                if (bm.bmBitsPixel <= 8)
                                {
                                Info.biClrUsed = 1 << bm.bmBitsPixel;
                                }else
                                Info.biClrUsed = 0;
                                Info.biXPelsPerMeter = 0;
                                Info.biYPelsPerMeter = 0;
                                bit1.GetBitmapBits(size2, buffer);
                                file1.Open(destination, CFile::modeCreate | CFile::modeWrite |CFile::typeBinary,0);
                                file1.Write(&bFileHeader, sizeof(BITMAPFILEHEADER));
                                file1.Write(&Info, sizeof(BITMAPINFOHEADER));
                                unsigned char alpha = 0;
                                for (int y = 0;y<size.cy;y++)
                                {
                                for (int x = 0;x<size.cx;x++)
                                {
                                //for reverse picture below
                                //z = (((size.cy - 1 - y)*size.cx) + (x)) * 3;
                                z = (((y)*size.cx) + (x)) * 3;
                                file1.Write(&buffer[z], 1);
                                file1.Write(&buffer[z + 1], 1);
                                file1.Write(&buffer[z + 2], 1);
                                }
                                for (int z = 0;z < (size1 - size2) / size.cy;z++)
                                {
                                file1.Write(&alpha, 1);
                                }
                                }
                                GlobalFree(buffer);
                                file1.Close();
                                file1.m_hFile = NULL;
                                }





                                share|improve this answer



















                                • 1





                                  Please note the android tag in the question

                                  – laalto
                                  Jul 5 '18 at 7:49
















                                -3














                                implementation save bitmap and load bitmap directly. fast and ease on mfc class



                                void CMRSMATH1Dlg::Loadit(TCHAR *destination, CDC &memdc)
                                {
                                CImage img;
                                PBITMAPINFO bmi;
                                BITMAPINFOHEADER Info;
                                BITMAPFILEHEADER bFileHeader;
                                CBitmap bm;
                                CFile file2;
                                file2.Open(destination, CFile::modeRead | CFile::typeBinary);
                                file2.Read(&bFileHeader, sizeof(BITMAPFILEHEADER));
                                file2.Read(&Info, sizeof(BITMAPINFOHEADER));
                                BYTE ch;
                                int width = Info.biWidth;
                                int height = Info.biHeight;
                                if (height < 0)height = -height;
                                int size1 = width*height * 3;
                                int size2 = ((width * 24 + 31) / 32) * 4 * height;
                                int widthnew = (size2 - size1) / height;
                                BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);
                                //////////////////////////
                                HGDIOBJ old;
                                unsigned char alpha = 0;
                                int z = 0;
                                z = 0;
                                int gap = (size2 - size1) / height;
                                for (int y = 0;y < height;y++)
                                {
                                for (int x = 0;x < width*3;x++)
                                {
                                file2.Read(&ch, 1);
                                buffer[z] = ch;
                                z++;
                                }
                                for (int z1 = 0;z1 <gap;z1++)
                                {
                                file2.Read(&ch,1);
                                }
                                }
                                bm.CreateCompatibleBitmap(&memdc, width, height);
                                bm.SetBitmapBits(size1,buffer);
                                old = memdc.SelectObject(&bm);
                                ///////////////////////////
                                //bm.SetBitmapBits(size1, buffer);
                                GetDC()->BitBlt(1, 95, width, height, &memdc, 0, 0, SRCCOPY);
                                memdc.SelectObject(&old);
                                bm.DeleteObject();
                                GlobalFree(buffer);
                                file2.Close();
                                }
                                void CMRSMATH1Dlg::saveit(CBitmap &bit1, CDC &memdc, TCHAR *destination)
                                {
                                BITMAP bm;
                                PBITMAPINFO bmi;
                                BITMAPINFOHEADER Info;
                                BITMAPFILEHEADER bFileHeader;
                                CFile file1;
                                CSize size = bit1.GetBitmap(&bm);
                                int z = 0;
                                BYTE ch = 0;
                                size.cx = bm.bmWidth;
                                size.cy = bm.bmHeight;
                                int width = size.cx;
                                int size1 = (size.cx)*(size.cy);
                                int size2 = size1 * 3;
                                size1 = ((size.cx * 24 + 31) / 32) *4* size.cy;
                                BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);
                                bFileHeader.bfType = 'B' + ('M' << 8);
                                bFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
                                bFileHeader.bfSize = bFileHeader.bfOffBits + size1;
                                bFileHeader.bfReserved1 = 0;
                                bFileHeader.bfReserved2 = 0;
                                Info.biSize = sizeof(BITMAPINFOHEADER);
                                Info.biPlanes = 1;
                                Info.biBitCount = 24;//bm.bmBitsPixel;//bitsperpixel///////////////////32
                                Info.biCompression = BI_RGB;
                                Info.biWidth =bm.bmWidth;
                                Info.biHeight =-bm.bmHeight;///reverse pic if negative height
                                Info.biSizeImage =size1;
                                Info.biClrImportant = 0;
                                if (bm.bmBitsPixel <= 8)
                                {
                                Info.biClrUsed = 1 << bm.bmBitsPixel;
                                }else
                                Info.biClrUsed = 0;
                                Info.biXPelsPerMeter = 0;
                                Info.biYPelsPerMeter = 0;
                                bit1.GetBitmapBits(size2, buffer);
                                file1.Open(destination, CFile::modeCreate | CFile::modeWrite |CFile::typeBinary,0);
                                file1.Write(&bFileHeader, sizeof(BITMAPFILEHEADER));
                                file1.Write(&Info, sizeof(BITMAPINFOHEADER));
                                unsigned char alpha = 0;
                                for (int y = 0;y<size.cy;y++)
                                {
                                for (int x = 0;x<size.cx;x++)
                                {
                                //for reverse picture below
                                //z = (((size.cy - 1 - y)*size.cx) + (x)) * 3;
                                z = (((y)*size.cx) + (x)) * 3;
                                file1.Write(&buffer[z], 1);
                                file1.Write(&buffer[z + 1], 1);
                                file1.Write(&buffer[z + 2], 1);
                                }
                                for (int z = 0;z < (size1 - size2) / size.cy;z++)
                                {
                                file1.Write(&alpha, 1);
                                }
                                }
                                GlobalFree(buffer);
                                file1.Close();
                                file1.m_hFile = NULL;
                                }





                                share|improve this answer



















                                • 1





                                  Please note the android tag in the question

                                  – laalto
                                  Jul 5 '18 at 7:49














                                -3












                                -3








                                -3







                                implementation save bitmap and load bitmap directly. fast and ease on mfc class



                                void CMRSMATH1Dlg::Loadit(TCHAR *destination, CDC &memdc)
                                {
                                CImage img;
                                PBITMAPINFO bmi;
                                BITMAPINFOHEADER Info;
                                BITMAPFILEHEADER bFileHeader;
                                CBitmap bm;
                                CFile file2;
                                file2.Open(destination, CFile::modeRead | CFile::typeBinary);
                                file2.Read(&bFileHeader, sizeof(BITMAPFILEHEADER));
                                file2.Read(&Info, sizeof(BITMAPINFOHEADER));
                                BYTE ch;
                                int width = Info.biWidth;
                                int height = Info.biHeight;
                                if (height < 0)height = -height;
                                int size1 = width*height * 3;
                                int size2 = ((width * 24 + 31) / 32) * 4 * height;
                                int widthnew = (size2 - size1) / height;
                                BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);
                                //////////////////////////
                                HGDIOBJ old;
                                unsigned char alpha = 0;
                                int z = 0;
                                z = 0;
                                int gap = (size2 - size1) / height;
                                for (int y = 0;y < height;y++)
                                {
                                for (int x = 0;x < width*3;x++)
                                {
                                file2.Read(&ch, 1);
                                buffer[z] = ch;
                                z++;
                                }
                                for (int z1 = 0;z1 <gap;z1++)
                                {
                                file2.Read(&ch,1);
                                }
                                }
                                bm.CreateCompatibleBitmap(&memdc, width, height);
                                bm.SetBitmapBits(size1,buffer);
                                old = memdc.SelectObject(&bm);
                                ///////////////////////////
                                //bm.SetBitmapBits(size1, buffer);
                                GetDC()->BitBlt(1, 95, width, height, &memdc, 0, 0, SRCCOPY);
                                memdc.SelectObject(&old);
                                bm.DeleteObject();
                                GlobalFree(buffer);
                                file2.Close();
                                }
                                void CMRSMATH1Dlg::saveit(CBitmap &bit1, CDC &memdc, TCHAR *destination)
                                {
                                BITMAP bm;
                                PBITMAPINFO bmi;
                                BITMAPINFOHEADER Info;
                                BITMAPFILEHEADER bFileHeader;
                                CFile file1;
                                CSize size = bit1.GetBitmap(&bm);
                                int z = 0;
                                BYTE ch = 0;
                                size.cx = bm.bmWidth;
                                size.cy = bm.bmHeight;
                                int width = size.cx;
                                int size1 = (size.cx)*(size.cy);
                                int size2 = size1 * 3;
                                size1 = ((size.cx * 24 + 31) / 32) *4* size.cy;
                                BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);
                                bFileHeader.bfType = 'B' + ('M' << 8);
                                bFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
                                bFileHeader.bfSize = bFileHeader.bfOffBits + size1;
                                bFileHeader.bfReserved1 = 0;
                                bFileHeader.bfReserved2 = 0;
                                Info.biSize = sizeof(BITMAPINFOHEADER);
                                Info.biPlanes = 1;
                                Info.biBitCount = 24;//bm.bmBitsPixel;//bitsperpixel///////////////////32
                                Info.biCompression = BI_RGB;
                                Info.biWidth =bm.bmWidth;
                                Info.biHeight =-bm.bmHeight;///reverse pic if negative height
                                Info.biSizeImage =size1;
                                Info.biClrImportant = 0;
                                if (bm.bmBitsPixel <= 8)
                                {
                                Info.biClrUsed = 1 << bm.bmBitsPixel;
                                }else
                                Info.biClrUsed = 0;
                                Info.biXPelsPerMeter = 0;
                                Info.biYPelsPerMeter = 0;
                                bit1.GetBitmapBits(size2, buffer);
                                file1.Open(destination, CFile::modeCreate | CFile::modeWrite |CFile::typeBinary,0);
                                file1.Write(&bFileHeader, sizeof(BITMAPFILEHEADER));
                                file1.Write(&Info, sizeof(BITMAPINFOHEADER));
                                unsigned char alpha = 0;
                                for (int y = 0;y<size.cy;y++)
                                {
                                for (int x = 0;x<size.cx;x++)
                                {
                                //for reverse picture below
                                //z = (((size.cy - 1 - y)*size.cx) + (x)) * 3;
                                z = (((y)*size.cx) + (x)) * 3;
                                file1.Write(&buffer[z], 1);
                                file1.Write(&buffer[z + 1], 1);
                                file1.Write(&buffer[z + 2], 1);
                                }
                                for (int z = 0;z < (size1 - size2) / size.cy;z++)
                                {
                                file1.Write(&alpha, 1);
                                }
                                }
                                GlobalFree(buffer);
                                file1.Close();
                                file1.m_hFile = NULL;
                                }





                                share|improve this answer













                                implementation save bitmap and load bitmap directly. fast and ease on mfc class



                                void CMRSMATH1Dlg::Loadit(TCHAR *destination, CDC &memdc)
                                {
                                CImage img;
                                PBITMAPINFO bmi;
                                BITMAPINFOHEADER Info;
                                BITMAPFILEHEADER bFileHeader;
                                CBitmap bm;
                                CFile file2;
                                file2.Open(destination, CFile::modeRead | CFile::typeBinary);
                                file2.Read(&bFileHeader, sizeof(BITMAPFILEHEADER));
                                file2.Read(&Info, sizeof(BITMAPINFOHEADER));
                                BYTE ch;
                                int width = Info.biWidth;
                                int height = Info.biHeight;
                                if (height < 0)height = -height;
                                int size1 = width*height * 3;
                                int size2 = ((width * 24 + 31) / 32) * 4 * height;
                                int widthnew = (size2 - size1) / height;
                                BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);
                                //////////////////////////
                                HGDIOBJ old;
                                unsigned char alpha = 0;
                                int z = 0;
                                z = 0;
                                int gap = (size2 - size1) / height;
                                for (int y = 0;y < height;y++)
                                {
                                for (int x = 0;x < width*3;x++)
                                {
                                file2.Read(&ch, 1);
                                buffer[z] = ch;
                                z++;
                                }
                                for (int z1 = 0;z1 <gap;z1++)
                                {
                                file2.Read(&ch,1);
                                }
                                }
                                bm.CreateCompatibleBitmap(&memdc, width, height);
                                bm.SetBitmapBits(size1,buffer);
                                old = memdc.SelectObject(&bm);
                                ///////////////////////////
                                //bm.SetBitmapBits(size1, buffer);
                                GetDC()->BitBlt(1, 95, width, height, &memdc, 0, 0, SRCCOPY);
                                memdc.SelectObject(&old);
                                bm.DeleteObject();
                                GlobalFree(buffer);
                                file2.Close();
                                }
                                void CMRSMATH1Dlg::saveit(CBitmap &bit1, CDC &memdc, TCHAR *destination)
                                {
                                BITMAP bm;
                                PBITMAPINFO bmi;
                                BITMAPINFOHEADER Info;
                                BITMAPFILEHEADER bFileHeader;
                                CFile file1;
                                CSize size = bit1.GetBitmap(&bm);
                                int z = 0;
                                BYTE ch = 0;
                                size.cx = bm.bmWidth;
                                size.cy = bm.bmHeight;
                                int width = size.cx;
                                int size1 = (size.cx)*(size.cy);
                                int size2 = size1 * 3;
                                size1 = ((size.cx * 24 + 31) / 32) *4* size.cy;
                                BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);
                                bFileHeader.bfType = 'B' + ('M' << 8);
                                bFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
                                bFileHeader.bfSize = bFileHeader.bfOffBits + size1;
                                bFileHeader.bfReserved1 = 0;
                                bFileHeader.bfReserved2 = 0;
                                Info.biSize = sizeof(BITMAPINFOHEADER);
                                Info.biPlanes = 1;
                                Info.biBitCount = 24;//bm.bmBitsPixel;//bitsperpixel///////////////////32
                                Info.biCompression = BI_RGB;
                                Info.biWidth =bm.bmWidth;
                                Info.biHeight =-bm.bmHeight;///reverse pic if negative height
                                Info.biSizeImage =size1;
                                Info.biClrImportant = 0;
                                if (bm.bmBitsPixel <= 8)
                                {
                                Info.biClrUsed = 1 << bm.bmBitsPixel;
                                }else
                                Info.biClrUsed = 0;
                                Info.biXPelsPerMeter = 0;
                                Info.biYPelsPerMeter = 0;
                                bit1.GetBitmapBits(size2, buffer);
                                file1.Open(destination, CFile::modeCreate | CFile::modeWrite |CFile::typeBinary,0);
                                file1.Write(&bFileHeader, sizeof(BITMAPFILEHEADER));
                                file1.Write(&Info, sizeof(BITMAPINFOHEADER));
                                unsigned char alpha = 0;
                                for (int y = 0;y<size.cy;y++)
                                {
                                for (int x = 0;x<size.cx;x++)
                                {
                                //for reverse picture below
                                //z = (((size.cy - 1 - y)*size.cx) + (x)) * 3;
                                z = (((y)*size.cx) + (x)) * 3;
                                file1.Write(&buffer[z], 1);
                                file1.Write(&buffer[z + 1], 1);
                                file1.Write(&buffer[z + 2], 1);
                                }
                                for (int z = 0;z < (size1 - size2) / size.cy;z++)
                                {
                                file1.Write(&alpha, 1);
                                }
                                }
                                GlobalFree(buffer);
                                file1.Close();
                                file1.m_hFile = NULL;
                                }






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Jul 5 '18 at 7:45









                                Amir RasouliAmir Rasouli

                                9




                                9








                                • 1





                                  Please note the android tag in the question

                                  – laalto
                                  Jul 5 '18 at 7:49














                                • 1





                                  Please note the android tag in the question

                                  – laalto
                                  Jul 5 '18 at 7:49








                                1




                                1





                                Please note the android tag in the question

                                – laalto
                                Jul 5 '18 at 7:49





                                Please note the android tag in the question

                                – laalto
                                Jul 5 '18 at 7:49


















                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11274715%2fsave-bitmap-to-file-function%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                MongoDB - Not Authorized To Execute Command

                                in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                                How to fix TextFormField cause rebuild widget in Flutter