web-dev-qa-db-de.com

Speichern Sie die Bitmap in der Dateifunktion

Ich versuche, eine Bitmap mit einer von mir erstellten Funktion direkt in einer Datei und einer bestimmten Datei zu speichern. Es funktioniert nicht. Es stürzt nach bitmap.compress ab (vor 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();

Fehlerprotokoll:

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)
32
Oliver Dixon
  1. Sie benötigen eine entsprechende Berechtigung in manifest.xml:

    <uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  2. out.flush() prüfe, ob out nicht null ist ..

  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();
    
75
Dheeresh Singh

Zwei Beispiele dienen mir als Referenz.

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;
}

und das hier

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");
}
14
Devon

In Kotlin:

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

anwendungsbeispiel:

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

Hier ist die Funktion, die Ihnen hilft

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();
            }    
        }
    }
5
Dhaval Solanki