create Temp Image File - Android android.graphics

Android examples for android.graphics:Image Load Save

Description

create Temp Image File

Demo Code

import java.io.File;
import java.io.FileOutputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.widget.Toast;

public class Main {

  public static final String TEMP_IMAGE_FILE_NAME = "temp.jpg";

  public static File createTempImageFile(Context context, Drawable drawable) {
    File cacheDir = context.getCacheDir();
    File file = null;/*from   w  w  w  .  j  a va 2  s .  c o m*/
    try {
      if (!cacheDir.isDirectory() || !cacheDir.exists())
        cacheDir.mkdir();
    } catch (Exception e) {
      Toast.makeText(context, "Create Folder Error about Cache Directory", Toast.LENGTH_SHORT).show();
    }
    try {
      file = new File(context.getCacheDir(), TEMP_IMAGE_FILE_NAME);
      if (file.exists()) {
        file.delete();
        file.createNewFile();
      }
      FileOutputStream fos = new FileOutputStream(file);

      Rect rect = drawable.getBounds();

      Bitmap bitmap = Bitmap.createBitmap(rect.right, rect.bottom, Bitmap.Config.ARGB_8888);
      Canvas canvas = new Canvas(bitmap);
      drawable.setBounds(0, 0, rect.right, rect.bottom);
      drawable.draw(canvas);

      bitmap.compress(CompressFormat.JPEG, 80, fos);
      fos.flush();
      fos.close();
    } catch (Exception e) {
      Toast.makeText(context, "Save Error about Image File", Toast.LENGTH_SHORT).show();
      e.printStackTrace();
    }
    return file;
  }

}

Related Tutorials