Android Drawable Create createTempImageFile(Context context, Drawable drawable)

Here you can find the source of createTempImageFile(Context context, Drawable drawable)

Description

create Temp Image File

Declaration

public static File createTempImageFile(Context context,
            Drawable drawable) 

Method Source Code

//package com.java2s;
import java.io.File;

import java.io.FileOutputStream;

import android.content.Context;

import android.graphics.Bitmap;

import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.Bitmap.CompressFormat;

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) {/*from w  ww .j  a va  2s.co m*/
        File cacheDir = context.getCacheDir();
        File file = null;
        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

  1. getDrawableFromUrl(String url)
  2. getPressedDrawable(int color)
  3. getDrawableByName(Context ctx, String name)
  4. getDrawable(final Context context, final String packageName, final int resourceID)
  5. drawableToTransitionDrawable( Drawable drawable)
  6. loadImageFromUrl(String url)