save Image And Recycle Bitmap - Android Graphics

Android examples for Graphics:Bitmap Recycle

Description

save Image And Recycle Bitmap

Demo Code


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

public class Main {
  private static final String LOG_TAG = "";
  private static final boolean PRETEND_NO_SD = false;
  private static final String IMAGE_OUTPUT_FILE_NAME = "as_recommended_by.jpg";

  public static String saveImageAndRecycleBitmap(final Context context, Bitmap bitmap) {
    OutputStream outputStream = null;

    try {//from   w w w .  j a v a  2 s.  c om
      final File targetFile;
      final File externalStorageDirectory = Environment.getExternalStorageDirectory();
      boolean useSdCard = !PRETEND_NO_SD && externalStorageDirectory.exists();
      if (useSdCard) {
        targetFile = new File(externalStorageDirectory, IMAGE_OUTPUT_FILE_NAME);
        if (targetFile.exists()) {
          targetFile.delete();
        }
        outputStream = new FileOutputStream(targetFile);

      } else {
        targetFile = context.getFileStreamPath(IMAGE_OUTPUT_FILE_NAME);
        outputStream = context.openFileOutput(IMAGE_OUTPUT_FILE_NAME, Context.MODE_WORLD_READABLE);
      }

      bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream);
      bitmap.recycle();
      bitmap = null;
      System.gc();
      System.gc();

      outputStream.flush();
      outputStream.close();
      return targetFile.getAbsolutePath();

    } catch (final Exception e) {
      Log.e(LOG_TAG, "Error saving image.", e);
    } finally {
      if (null != bitmap) {
        bitmap.recycle();
        System.gc();
        System.gc();
      }
      if (null != outputStream) {
        try {
          outputStream.close();
        } catch (IOException e) {
          // Do nothing.
        }
      }
    }

    return null;
  }
}

Related Tutorials