Android Tutorial - 2D Graphics : Image

Capture Image

   

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Button
    android:id="@+id/capture"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Take a Picture"
  />
  <ImageView
    android:id="@+id/image"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scaleType="centerInside"
  />
</LinearLayout>
package app.test;

import java.io.File;
import java.io.FileInputStream;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MyActivity extends Activity {
    
    private static final int REQUEST_IMAGE = 100;
    
    Button captureButton;
    ImageView imageView;
    File destination;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        captureButton = (Button)findViewById(R.id.capture);
        captureButton.setOnClickListener(listener);
        
        imageView = (ImageView)findViewById(R.id.image);
        
        destination = new File(Environment.getExternalStorageDirectory(),"image.jpg");
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
            //Bitmap userImage = (Bitmap)data.getExtras().get("data");
            try {
                FileInputStream in = new FileInputStream(destination);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 10; //Downsample 10x
                Bitmap userImage = BitmapFactory.decodeStream(in, null, options);
                imageView.setImageBitmap(userImage);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
    }
    
    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //Add extra to save full-image somewhere
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
            Toast.makeText(MyActivity.this, Uri.fromFile(destination).toString(), Toast.LENGTH_SHORT).show();
            startActivityForResult(intent, REQUEST_IMAGE);
        }
    };
}

extends BaseAdapter to create Image adapter

   
package app.test;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class Test extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    setTitle("GridViewActivity");
    GridView gridview = (GridView) findViewById(R.id.grid_view);
    gridview.setAdapter(new ImageAdapter(this));
  }

  public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    public ImageAdapter(Context c) {
      mContext = c;
    }

    public int getCount() {
      return mThumbIds.length;
    }

    public Object getItem(int position) {
      return null;
    }

    public long getItemId(int position) {
      return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
      ImageView imageView;
      if (convertView == null) {
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
      } else {
        imageView = (ImageView) convertView;
      }

      imageView.setImageResource(mThumbIds[position]);
      return imageView;
    }

    private Integer[] mThumbIds = { R.drawable.icon, R.drawable.icon, };
  }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
 
       
<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/grid_view"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/> 
 

extends BaseAdapter to create adapter for images

   

package app.test;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

public class Test extends Activity {
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
          Gallery gallery = (Gallery)findViewById(R.id.gallery);
          ManateeAdapter manateeAdapter = new ManateeAdapter(this);
          gallery.setAdapter(manateeAdapter);
      }
      public static class ManateeAdapter extends BaseAdapter {
          private static final String TAG = "ManateeAdapter";
          private static int convertViewCounter = 0;
      private Context mContext;
          private LayoutInflater mInflater;

          static class ViewHolder {
              ImageView image;
          }
          
          private int[] manatees = {
                  R.drawable.icon, R.drawable.icon};
          
          private Bitmap[] manateeImages = new Bitmap[manatees.length];
          private Bitmap[] manateeThumbs = new Bitmap[manatees.length];

          public ManateeAdapter(Context context) {
            Log.v(TAG, "Constructing ManateeAdapter");
            this.mContext = context;
            mInflater = LayoutInflater.from(context);
            
            for(int i=0; i<manatees.length; i++) {
              manateeImages[i] = BitmapFactory.decodeResource(
                  context.getResources(), manatees[i]);
              manateeThumbs[i] = Bitmap.createScaledBitmap(manateeImages[i],
                  100, 100, false);
            }
          }
          
        public int getCount() {
          Log.v(TAG, "in getCount()");
          return manatees.length;
        }

        public int getViewTypeCount() {
          Log.v(TAG, "in getViewTypeCount()");
          return 1;
        }
        
        public int getItemViewType(int position) {
          Log.v(TAG, "in getItemViewType() for position " + position);
          return 0;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
              ViewHolder holder;
              
              Log.v(TAG, "in getView for position " + position + 
                  ", convertView is " +
                  ((convertView == null)?"null":"being recycled"));

              if (convertView == null) {
                  convertView = mInflater.inflate(R.layout.row, null);
                  convertViewCounter++;
                  Log.v(TAG, convertViewCounter + " convertViews have been created");

                  holder = new ViewHolder();
                  holder.image = (ImageView) convertView.findViewById(R.id.gridImageView);

                  convertView.setTag(holder);
              } else {
                  holder = (ViewHolder) convertView.getTag();
              }

              holder.image.setImageBitmap(manateeImages[position]);

              return convertView;
          }

        public Object getItem(int position) {
          Log.v(TAG, "in getItem() for position " + position);
          return manateeImages[position];
        }

        public long getItemId(int position) {
          Log.v(TAG, "in getItemId() for position " + position);
          return position;
        }
      }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- This file is at /res/layout/gallery.xml -->
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gallery"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
//row.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridImageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#555"
    android:scaleType="centerInside"
    android:padding="5dip"
    android:maxHeight="50dip"
    android:maxWidth="50dip"
  />

Capture Image and display

   

package app.test;

import java.io.File;
import java.util.TimeZone;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class Test extends Activity implements MediaScannerConnectionClient {
  private File myImageFile = null;
  private Uri myPicture = null;
  private MediaScannerConnection conn = null;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    public void captureImage(View view)
    {
      ContentValues values = new ContentValues();
        values.put(Media.TITLE, "My demo image");
        values.put(Media.DESCRIPTION, "Image Captured by Camera via an Intent");
        TimeZone myTZ = TimeZone.getDefault();
        Time now = new Time();
        values.put(Media.DATE_TAKEN, now.toMillis(false) - myTZ.getRawOffset());

        myPicture = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
        myImageFile.delete();
        myPicture = Uri.fromFile(myImageFile);
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        i.putExtra(MediaStore.EXTRA_OUTPUT, myPicture);

        startActivityForResult(i, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==0 && resultCode==Activity.RESULT_OK)
        {
          startScan();
        }
    }
    
    private void startScan()
    {
        if(conn !=null)
        {
            conn.disconnect();
        }
        if(myImageFile.isFile()) {
            conn = new MediaScannerConnection(this, this);
            conn.connect();
        }
        else {
            Toast.makeText(this,
                "Image file does not exist?!?!",
                Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    public void onMediaScannerConnected() {
        conn.scanFile(myImageFile.getPath(), null);
    }
    @Override
    public void onScanCompleted(String path, Uri uri) {
        try {
            if (uri != null) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(uri);
                startActivity(intent);
            }
        } finally {
            conn.disconnect();
            conn = null;
        } 
    }
}

Load up the image's dimensions

   
package app.test;

import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class Test extends Activity implements OnClickListener {
  ImageView chosenImageView;
  Button choosePicture;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    chosenImageView = (ImageView) this.findViewById(R.id.ChosenImageView);
    choosePicture = (Button) this.findViewById(R.id.ChoosePictureButton);

    choosePicture.setOnClickListener(this);
  }

  public void onClick(View v) {
    Intent choosePictureIntent = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(choosePictureIntent, 0);
  }

  protected void onActivityResult(int requestCode, int resultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (resultCode == RESULT_OK) {
      Uri imageFileUri = intent.getData();

      Display currentDisplay = getWindowManager().getDefaultDisplay();
      int dw = currentDisplay.getWidth();
      int dh = currentDisplay.getHeight() / 2 - 100;

      try {
        
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory
            .decodeStream(getContentResolver().openInputStream(
                imageFileUri), null, bmpFactoryOptions);

        int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
            / (float) dh);
        int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
            / (float) dw);

        if (heightRatio > 1 && widthRatio > 1) {
          if (heightRatio > widthRatio) {
            bmpFactoryOptions.inSampleSize = heightRatio;
          } else {
            bmpFactoryOptions.inSampleSize = widthRatio;
          }
        }
        bmpFactoryOptions.inJustDecodeBounds = false;
        bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);
        Bitmap alteredBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp
            .getHeight(), bmp.getConfig());
        Canvas canvas = new Canvas(alteredBitmap);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        // Decrease Saturation
        cm.setSaturation(.5f);
        paint.setColorFilter(new ColorMatrixColorFilter(cm));
        Matrix matrix = new Matrix();
        canvas.drawBitmap(bmp, matrix, paint);
        ImageView alteredImageView = (ImageView) this
            .findViewById(R.id.AlteredImageView);
        alteredImageView.setImageBitmap(alteredBitmap);
        chosenImageView.setImageBitmap(bmp);
      } catch (Exception e) {
        Log.v("ERROR", e.toString());
      }
    }
  }
}

//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Choose Picture" android:id="@+id/ChoosePictureButton"/>

<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ChosenImageView"></ImageView>
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/AlteredImageView"></ImageView>
</LinearLayout>

Lazy Loading Image

//package com.mediaportal.ampdroid.lists;


public class LazyLoadingImage {
   private String mImageUrl;
   private String mImageCacheName;
   private int mMaxWidth;
   private int mMaxHeight;
   private ImageType mImageType;
   public enum ImageType { Media, TvLogo };
   
   public LazyLoadingImage(String _url, String _cache, int _maxWidth, int _maxHeight) {
      mImageUrl = _url;
      mImageCacheName = _cache;
      mMaxWidth = _maxWidth;
      mMaxHeight = _maxHeight;
   }
   
   public void setImageType(ImageType _type){
      mImageType = _type;
   }
   
   public ImageType getImageType(){
      return mImageType;
   }
   
   /**
    * The url of the image that should be loaded on demand
    * @return Url to the image
    */
   public String getImageUrl() {
      return mImageUrl;
   }
   
   /**
    * The url of the image that should be loaded on demand
    * @param _imageUrl Url to the image
    */
   public void setImageUrl(String _imageUrl) {
      this.mImageUrl = _imageUrl;
   }
   
   /**
    * Name of image in cache
    * @return The path of the image (once cached) relative to the cache root
    */
   public String getImageCacheName() {
      return mImageCacheName;
   }
   
   /**
    * Name of image in cache
    * @param _cacheName The path of the image (once cached) relative to the cache root
    */
   public void setImageCacheName(String _cacheName) {
      this.mImageCacheName = _cacheName;
   }
   public int getMaxWidth() {
      return mMaxWidth;
   }
   public void setMaxWidth(int _maxWidth) {
      this.mMaxWidth = _maxWidth;
   }
   public int getMaxHeight() {
      return mMaxHeight;
   }
   public void setMaxHeight(int _maxHeight) {
      this.mMaxHeight = _maxHeight;
   }
   
   
}

Resize Image

   
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

class MyUtils {
  public MyUtils() {
    
  }
  
  public static Drawable resizeImage(Context ctx, int resId, int w, int h) {

      // load the origial Bitmap
      Bitmap BitmapOrg = BitmapFactory.decodeResource(ctx.getResources(),
                                                      resId);

      int width = BitmapOrg.getWidth();
      int height = BitmapOrg.getHeight();
      int newWidth = w;
      int newHeight = newWidth * height / width;

      // calculate the scale
      float scaleWidth = ((float) newWidth) / width;
      float scaleHeight = ((float) newHeight) / height;

      // create a matrix for the manipulation
      Matrix matrix = new Matrix();
      // resize the Bitmap
      matrix.postScale(scaleWidth, scaleHeight);
      // if you want to rotate the Bitmap
      // matrix.postRotate(45);

      // recreate the new Bitmap
      Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0,
                                                 width, height, matrix, true);

      // make a Drawable from Bitmap to allow to set the Bitmap
      // to the ImageView, ImageButton or what ever
      return new BitmapDrawable(resizedBitmap);

    }
}

Fit Image No Margin

//package com.akjava.lib.android.image;



import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory.Options;
import android.util.Log;

/**
 * 
 * @author aki
 * @version 1.0
 * ?????????????
 * ????????????????
 *
 */
 class ImageUtils {
  public static final String[] imageExtensions={"jpg","png","jpeg","gif"};
  
  private ImageUtils(){}

  /**
   * ????????????????????????????????????????
   * ????????????????
   * 
   * @param baseImage ???
   * @param width ??
   * @param height ??
   * @return  ?????????????????
   */
  public static Bitmap fitImageNoMargin(Bitmap baseImage,int width,int height){
    
    Point pt=calculateFitImage(baseImage,width,height,null);//TODO gc free
    Bitmap resizedBitmap = Bitmap.createScaledBitmap(baseImage,
        pt.x, pt.y, true); 
    return resizedBitmap;
  }
  
  /**
   * ????????????????????????????
   * 
   * @param baseImage
   * @param width
   * @param height
   * @param receiver
   * @return
   */
  public static Point calculateFitImage(Bitmap baseImage,int width,int height,Point receiver){
    if(baseImage==null){
      throw new RuntimeException("baseImage is null");
    }
    if(receiver==null){
      receiver=new Point();
    }
    int dw=width;
    int dh=height;
    
    
    if(dw!=0 && dh!=0 ){
      double waspect=(double)dw/baseImage.getWidth();
      double haspect=(double)dh/baseImage.getHeight();
      if(waspect>haspect){//fit h
        dw=(int) (baseImage.getWidth()*haspect);
        
      }else{
        dh=(int)(baseImage.getHeight()*waspect);
      }
    }
    receiver.x=dw;
    receiver.y=dh;
    return receiver;
  }
}

To Rotate Texture Image

//package com.akjava.lib.android.image;



import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory.Options;
import android.util.Log;

/**
 * 
 * @author aki
 * @version 1.0
 * ?????????????
 * ????????????????
 *
 */
class ImageUtils {
  public static final String[] imageExtensions={"jpg","png","jpeg","gif"};
  
  private ImageUtils(){}

  /**
   * ????????????????????????????????????????
   * ????????????????
   * 
   * @param baseImage ???
   * @param width ??
   * @param height ??
   * @return  ?????????????????
   */
  public static Bitmap fitImageNoMargin(Bitmap baseImage,int width,int height){
    
    Point pt=calculateFitImage(baseImage,width,height,null);//TODO gc free
    Bitmap resizedBitmap = Bitmap.createScaledBitmap(baseImage,
        pt.x, pt.y, true); 
    return resizedBitmap;
  }
  
  /**
   * ??????????????????????????????????
   * ?????????????????
   * ??????????????????????
   * 
   * @param path
   * @param width
   * @param config
   * @return
   */
  public static Bitmap sampleSizeOpenBitmapByWidth(String path,int width,Bitmap.Config config){
    Point size=parseJpegSize(path, null);
    int rw=size.x/width;
    
    int sampleSize=Math.max(rw, 1);
    Bitmap bitmap=sampleSizeOpenBitmap(path, sampleSize);
    return bitmap;
  }
  
/**
 * ??????????????????????????
 * 
 * 
 * @param path
 * @param width
 * @param height
 * @param config null????Bitmap.Config.RGB_565??????
 * @return ?????????????????????????????
 */
  public static Bitmap fitImage(String path,int width,int height,Bitmap.Config config){
    //TODO set bgcolor
    Point size=parseJpegSize(path, null);
    int rw=size.x/width;
    int rh=size.y/height;
    int sampleSize=Math.min(rw, rh);
    sampleSize=Math.max(sampleSize, 1);
    Bitmap bitmap=sampleSizeOpenBitmap(path, sampleSize,config);
    return fitImage(bitmap, width, height, config, true);
  }
  
    
  
  
  /**
   * ????????????
   * 
   * @param baseImage
   * @param width
   * @param height
   * @param config null????Bitmap.Config.RGB_565??????
   * @param doRecycleBase ???bitmap?recycle???????true??
   * @return ?????????????????????????????
   */
  public static Bitmap fitImage(Bitmap baseImage,int width,int height,Bitmap.Config config,boolean doRecycleBase){
    if(baseImage==null){
      throw new RuntimeException("baseImage is null");
    }
    if(config==null){
      config=Bitmap.Config.RGB_565;
    }
    Point resizedP=calculateFitImage(baseImage, width, height, null);//TODO gc free
    
    
        Bitmap resizedBitmap =  Bitmap.createScaledBitmap(baseImage,
        resizedP.x, resizedP.y, true); 
        
        if(doRecycleBase){//to avoid memory error
          baseImage.recycle();
        }
        
        Bitmap returnBitmap=Bitmap.createBitmap(width, height, config);
        Canvas canvas=new Canvas(returnBitmap);
        canvas.drawBitmap(resizedBitmap, (width-resizedP.x)/2, (height-resizedP.y)/2,null);
        resizedBitmap.recycle();
        
    return returnBitmap;
  }
  
  /**
   * ????????????????????????????
   * 
   * @param baseImage
   * @param width
   * @param height
   * @param receiver
   * @return
   */
  public static Point calculateFitImage(Bitmap baseImage,int width,int height,Point receiver){
    if(baseImage==null){
      throw new RuntimeException("baseImage is null");
    }
    if(receiver==null){
      receiver=new Point();
    }
    int dw=width;
    int dh=height;
    
    
    if(dw!=0 && dh!=0 ){
      double waspect=(double)dw/baseImage.getWidth();
      double haspect=(double)dh/baseImage.getHeight();
      if(waspect>haspect){//fit h
        dw=(int) (baseImage.getWidth()*haspect);
        
      }else{
        dh=(int)(baseImage.getHeight()*waspect);
      }
    }
    receiver.x=dw;
    receiver.y=dh;
    return receiver;
  }
  /**
   *  ????????????????????recyle?????
   *  
   * @param baseImage
   * @param width
   * @param height
   * @return
   */
  public static Bitmap toTextureImage(Bitmap baseImage,int width,int height){
    return toTextureImage(baseImage, width, height,false);
  }
  
  /**
   * PNG ??????????
   * 
   * @param bitmap
   * @param output
   * @return
   * @throws FileNotFoundException
   */
  public static boolean writeAsPng(Bitmap bitmap,String output) throws FileNotFoundException{
    return bitmap.compress(Bitmap.CompressFormat.PNG, 1, new FileOutputStream(output));
  }
  
  /**
   * ???????????????
   * 
   * @param baseImage
   * @param width must be divided 2 (like 256 or 512)
   * @param height must be divided 2 (like 256 or 512)
   * @return
   */
  public static Bitmap toTextureImage(Bitmap baseImage,int width,int height,boolean recycle){
  
    int owidth = baseImage.getWidth(); 
        int oheight = baseImage.getHeight(); 
       
        
        // calculate the scale - in this case = 0.4f 
        float scaleWidth = ((float) width) / owidth; 
        float scaleHeight = ((float) height) / oheight; 
    
      
    Matrix matrix = new Matrix(); 
      
        // resize the bit map 
        matrix.postScale(scaleWidth, -scaleHeight); 
        // rotate the Bitmap 
        //matrix.postRotate(-180); 
        
        Bitmap resizedBitmap = Bitmap.createBitmap(baseImage, 0, 0, 
            owidth, oheight, matrix, true); 
        if(recycle){
          baseImage.recycle();
        }
        Log.i("myapp","resized:"+resizedBitmap.getWidth()+"x"+resizedBitmap.getHeight());
    
    return resizedBitmap;
  }
  
  /**
   * ?????????????????????????
   * 
   * @param baseImage
   * @param width
   * @param height
   * @param rotateRight
   * @return
   */
  public static Bitmap toRotateTextureImage(Bitmap baseImage,int width,int height,boolean rotateRight){
    
    int owidth = baseImage.getWidth(); 
        int oheight = baseImage.getHeight(); 
       
        
        // calculate the scale - in this case = 0.4f 
        float scaleWidth = ((float) width) / owidth; 
        float scaleHeight = ((float) height) / oheight; 
    
      
    Matrix matrix = new Matrix(); 
      
        // resize the bit map 
        matrix.postScale(scaleWidth, -scaleHeight); 
        // rotate the Bitmap 
        if(rotateRight){
        matrix.postRotate(90); 
        }else{
        matrix.postRotate(-90);   
        }
        
        Bitmap resizedBitmap = Bitmap.createBitmap(baseImage, 0, 0, 
            owidth, oheight, matrix, true); 
        
        Log.i("myapp","resized:"+resizedBitmap.getWidth()+"x"+resizedBitmap.getHeight());
    
    return resizedBitmap;
  }
  
  /**
   * ???????????sampleSize???????width?height??????????
   */
  public static int lastSampleSize=1;
  //public static BitmapFactory.Options bitmapOption;//cancel????????denger
  
  /**
   *  ?????????????????????
   *  ???????????????????????????????????????
   *  
   * @param path
   * @param startSize
   * @param config
   * @return
   */
  public static Bitmap sampleSizeOpenBitmap(String path, int startSize,
      Config config) {
    BitmapFactory.Options bitmapOption = new BitmapFactory.Options();
    bitmapOption.inPreferredConfig=config;
    return sampleSizeOpenBitmap(path, startSize,bitmapOption);
  }
  
  /**
   *  ?????????????????????
   *  ???????????????????????????????????????
   *  
   * @param path
   * @param startSize
   * @param bitmapOption
   * @return
   */
  public static Bitmap sampleSizeOpenBitmap(String path, int startSize,
      Options bitmapOption) {    
    int inSampleSize=startSize;
    Bitmap bitmap=null;
    for(int i=0;i<10;i++){
      
    try{
      bitmapOption.inSampleSize=inSampleSize;
      bitmap=BitmapFactory.decodeFile(path,bitmapOption);
      //Log.i("imageutils","decoded bitmap:"+bitmapOption.inSampleSize);
      lastSampleSize=inSampleSize;
      if(bitmap==null){
        System.gc();//ready for next
      }
    }catch(Error e){
      Log.i("imageutils","faild load:"+inSampleSize+" "+path);
    }
    if(bitmap!=null || bitmapOption.mCancel){
      break;
    }else{
      //inSampleSize*=2;
      inSampleSize+=1;
    }
  }
    return bitmap;
  }
  
  /**
   * ??????????????????????
   * 
   * @param path
   * @param width
   * @param height
   * @param config
   * @return
   */
  public static Bitmap sampleSizeOpenBitmap(String path,int width,int height,Config config){
    Point size=parseJpegSize(path, null);
    int rw=size.x/width;
    int rh=size.y/height;
    int sampleSize=Math.min(rw, rh);
    sampleSize=Math.max(sampleSize, 1);
    return sampleSizeOpenBitmap(path, sampleSize,config);
  }
  
  /**
   * MemoryError????????????Content://????????
   * ???? RGB565?????
   * @see MediaImageUtils#loadImageFileOrUri(android.content.ContentResolver, String)
   * @param path
   * @param startSize
   * @return
   */
  
  public static Bitmap sampleSizeOpenBitmap(String path,int startSize){
    return sampleSizeOpenBitmap(path, startSize,(Config) null);
  }
  
  /**
   * ????????????????????
   * @param name
   * @return
   */
  public static boolean isImageFile(String name){
    for (int i = 0; i < imageExtensions.length; i++) {
    if(name.toLowerCase().endsWith("."+imageExtensions[i]))  {
      return true;
    }
    }
    return false;
  }
  
  /**
   * ?????????
   * 
   * @param bitmap
   * @param rect
   * @return
   */
  public static Bitmap cropBitmap(Bitmap bitmap,Rect rect){
    int w=rect.right-rect.left;
    int h=rect.bottom-rect.top;
    Bitmap ret=Bitmap.createBitmap(w, h, bitmap.getConfig());
    Canvas canvas=new Canvas(ret);
    canvas.drawBitmap(bitmap, -rect.left, -rect.top, null);
    return ret;
  }
  
  /**
   * JPEG???????????
   * 
   * @param path
   * @param receiver
   * @return
   */
  public static Point parseJpegSize(String path,Point receiver){
    if(receiver==null){
      receiver=new Point();
    }
    
    Options option=new BitmapFactory.Options();
    option.inJustDecodeBounds=true;
    BitmapFactory.decodeFile(path,option);
    receiver.x=option.outWidth;
    receiver.y=option.outHeight;
    return receiver;
  }
  
}

Image Resize

   
//package com.day.util;

import java.io.FileNotFoundException;
import java.io.IOException;

import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.util.Log;

public class ImageResize {
  private Context mContext;
  private int mWidth;
  private int mHeight;
  private Uri mImageUri;
  private BitmapFactory.Options mBitMapOptions;
  private Bitmap mBitMap;
  private Bitmap tempBitMap;
  
  public ImageResize(Context context, int width, int height, Uri imgUri){
    this.mContext = context;
    this.mWidth = width;
    this.mHeight = height;
    this.mImageUri = imgUri;
  }
  
  public Bitmap getResizeImage(){
    ContentResolver resolver = mContext.getContentResolver();
    mBitMapOptions = new BitmapFactory.Options();
    
    if(mImageUri != null){
      ParcelFileDescriptor fd = null;
      try {
        fd = resolver.openFileDescriptor(mImageUri, "r");
        int sampleSize = 1;
        
        mBitMapOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, mBitMapOptions);
        
        int nextWidth = mBitMapOptions.outWidth >> 1;
        int nextHeight = mBitMapOptions.outHeight >> 1;
        
        while(nextWidth > mWidth && nextHeight > mHeight){
          sampleSize <<= 1;
          nextWidth >>= 1;
          nextHeight >>= 1;
        }
        
        mBitMapOptions.inSampleSize = sampleSize;
        mBitMapOptions.inJustDecodeBounds = false;
        
        mBitMap = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, mBitMapOptions);
        Log.d("Result","Image use Size : " +mWidth+"," +mHeight);
        Log.d("Result","Image Size : " +mBitMap.getWidth()+"," + mBitMap.getHeight());
        Log.d("Result","aa : " +(mWidth*mBitMap.getHeight())/mBitMap.getWidth());
        if(mBitMap!=null){
          if(mBitMapOptions.outWidth != mWidth || mBitMapOptions.outHeight != mHeight){ 
            //??????? :  ???? ????????  =  (???? ???????? * ?????????) / ????????? 
            tempBitMap = Bitmap.createScaledBitmap(mBitMap, mWidth, (mWidth*mBitMap.getHeight())/mBitMap.getWidth(), true);
            mBitMap.recycle();
            mBitMap = tempBitMap;
          }
        }
        
        return mBitMap;
        
      } catch (FileNotFoundException e) {
        Log.e(getClass().getSimpleName(), e.getMessage(), e);
      } finally {
          try { if(fd != null) fd.close(); } catch (IOException e) { Log.e(getClass().getSimpleName(), e.getMessage(), e);}
          if(mBitMap != null) mBitMap = null;
          if(tempBitMap != null) tempBitMap = null;
      }
    }
    return null;
  }
}

Create Image and resize Image

   

//package com.runlog;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * AppUtils is a helper class that makes it easy to perform frequently used
 * tasks in Android development.
 * 
 * @author Nazmul Idris
 * @version 1.0
 * @since Jul 8, 2008, 2:35:39 PM
 */
public class AppUtils {

  /**
   * 127.0.0.1 in the emulator points back to itself. Use this if you want to
   * access your host OS
   */
  public static String EmulatorLocalhost = "10.0.2.2";

  /**
   * shows a short message on top of your app... it goes away automatically
   * after a short delay
   */
  public static void showToastShort(Activity a, String msg) {
    Toast.makeText(a, msg, Toast.LENGTH_SHORT).show();
  }

  /**
   * shows a short message on top of your app... it goes away automatically
   * after a long delay
   */
  public static void showToastLong(Activity a, String msg) {
    Toast.makeText(a, msg, Toast.LENGTH_LONG).show();
  }

  public static void showToast(Activity a, String msg, int length) {
    Toast.makeText(a, msg, length).show();
  }

  /**
   * create an image view, given a drawable. you can set the max size of this
   * imageview as well.
   * 
   * @param iconWidth
   *            -1 means dont set this
   * @param iconHeight
   *            -1 means dont set this
   * @param imageRes
   *            -1 means dont set this
   */
  public static ImageView createImageView(Context activity, int iconWidth,
      int iconHeight, int imageRes) {
    ImageView icon = new ImageView(activity);
    icon.setAdjustViewBounds(true);
    icon.setScaleType(ImageView.ScaleType.FIT_CENTER);

    if (iconHeight != -1)
      icon.setMaxHeight(iconHeight);
    if (iconWidth != -1)
      icon.setMaxWidth(iconWidth);

    if (imageRes != -1)
      icon.setImageResource(imageRes);
    return icon;
  }

  /** simply resizes a given drawable resource to the given width and height */
  public static Drawable resizeImage(Context ctx, int resId, int iconWidth,
      int iconHeight) {

    // load the origial Bitmap
    Bitmap BitmapOrg = BitmapFactory.decodeResource(ctx.getResources(),
        resId);

    int width = BitmapOrg.getWidth();
    int height = BitmapOrg.getHeight();
    int newWidth = iconWidth;
    int newHeight = iconHeight;

    // calculate the scale
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;

    // create a matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the Bitmap
    matrix.postScale(scaleWidth, scaleHeight);

    // if you want to rotate the Bitmap
    // matrix.postRotate(45);

    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
        height, matrix, true);

    // make a Drawable from Bitmap to allow to set the Bitmap
    // to the ImageView, ImageButton or what ever
    return new BitmapDrawable(resizedBitmap);

  }

}// end class AppUtils

image To Byte

   

//package cn.cate.service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageUtils {
  
  public static byte[] imageToByte(String imagePath){
    InputStream is;
    ByteArrayOutputStream bs = new ByteArrayOutputStream();
    try {
      URL url = new URL(imagePath);
      HttpURLConnection conn = (HttpURLConnection)url.openConnection();
      conn.setRequestMethod("GET");
      conn.setReadTimeout(5 * 1000);
      if(conn.getResponseCode() == 200){
        is = conn.getInputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = is.read(buffer)) != -1){
          bs.write(buffer, 0, len);
        }
      }else{
        throw new Exception("????");
      }
      
      bs.close();
      is.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return bs.toByteArray();
  }
}

Image Loader

   
//package com.discogs.cupcake.utils;
 
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.widget.ImageView;
 
public class ImageLoader 
{
  static private ImageLoader _instance;
  static public ImageLoader getInstance() 
  {
    if (_instance == null) 
    {
      _instance = new ImageLoader();
    }
    return _instance;
  }
 
  private HashMap<String , Bitmap> _urlToBitmap;
  private Queue<Group> _queue;
  private DownloadThread _thread;
  private Bitmap _missing;
  private boolean _busy;
 
    /**
     * Constructor
     */
  private ImageLoader () 
  {
    _urlToBitmap = new HashMap<String , Bitmap>();
    _queue = new LinkedList<Group>();
    _busy = false;
  }
 
  public Bitmap get(String url) 
  {
    return _urlToBitmap.get(url);
  }
 
  public void load(ImageView image, String url) 
  {
    load(image, url, false);
  }
 
  public void load(ImageView image, String url, boolean cache) 
  {
    if (_urlToBitmap.get(url) != null) 
    {
      if (image!=null) 
      {
        image.setImageBitmap(_urlToBitmap.get(url));
      }
    } 
    else 
    {
      image.setImageBitmap(null);
      queue(image, url, cache);
    }
  }
 
  public void queue(ImageView image, String url, boolean cache) 
  {
    Iterator<Group> it = _queue.iterator();
  
    if (image!=null) 
    {
      while (it.hasNext()) 
      {
        if (it.next().image.equals(image)) 
        {
          it.remove();
          break;
        }
      }
    } 
    else if (url!=null) 
    {
      while (it.hasNext()) 
      {
        if (it.next().url.equals(url)) 
        {
          it.remove();
          break;
        }
      }
    }
    
    _queue.add(new Group(image, url, null, cache));
    loadNext();
  }
 
  public void clearQueue() 
  {
    _queue = new LinkedList<Group>();
  }
 
  public void clearCache() 
  {
    _urlToBitmap = new HashMap<String , Bitmap>();
  }
 
  public void cancel() 
  {
    clearQueue();
  
    if ( _thread != null ) 
    {
      _thread.disconnect();
      _thread = null;
    }
  }
 
  public void setMissingBitmap(Bitmap bitmap) 
  {
    _missing = bitmap;
  }
 
  private void loadNext() 
  {
    Iterator<Group> it = _queue.iterator();
    
    if (!_busy && it.hasNext()) 
    {
      _busy = true;
      Group group = it.next();
      it.remove();
      
      // double check image availability
      if (_urlToBitmap.get(group.url) != null) 
      {
        if (group.image!=null) 
        {
          group.image.setImageBitmap(_urlToBitmap.get(group.url));
        }
        
        _busy = false;
        loadNext();
      } 
      else 
      {
        _thread = new DownloadThread(group);
        _thread.start();
      }
    }
  }
 
  private void onLoad() 
  {
    if (_thread != null) 
    {
      Group group = _thread.group;
    
      if (group.bitmap != null) 
      {
        if (group.cache) 
        {
          _urlToBitmap.put(group.url, group.bitmap);
        }
        
        if (group.image != null) 
        {
          group.image.setImageBitmap(group.bitmap);
        }
      } 
      else if (_missing != null) 
      {
        if (group.image != null) 
        {
          group.image.setImageBitmap(_missing);
        }
      }
    }
    
    _thread = null;
    _busy = false;
    loadNext();
  }
 
  private class Group 
  {
    public Group(ImageView image, String url, Bitmap bitmap, boolean cache) 
    {
      this.image = image;
      this.url = url;
      this.bitmap = bitmap;
      this.cache = cache;
    }
    public ImageView image;
    public String url;
    public Bitmap bitmap;
    public boolean cache;
  }
 
  private class DownloadThread extends Thread 
  {
    final Handler threadHandler = new Handler();
      final Runnable threadCallback = new Runnable() 
      {
          public void run() 
          {
            onLoad();
          }
      };
    private HttpURLConnection _conn;
    public Group group;
    public DownloadThread(Group group) 
    {
      this.group = group;
    }
 
    @Override
    public void run() 
    {
      InputStream inStream = null;
      _conn = null;
    
      try 
      {
        _conn = (HttpURLConnection) new URL(group.url).openConnection();
        _conn.setDoInput(true);
        _conn.connect();
        inStream = _conn.getInputStream();
        group.bitmap = BitmapFactory.decodeStream(inStream);
        inStream.close();
        _conn.disconnect();
        inStream = null;
        _conn = null;
      }
      catch (Exception ex) 
      {
        // nothing
      }
      
      if (inStream != null) 
      {
        try 
        {
          inStream.close();
        } 
        catch (Exception ex) 
        {
        }
      }
      disconnect();
      inStream = null;
      _conn = null;
      threadHandler.post(threadCallback);
    }
 
    public void disconnect() 
    {
      if (_conn != null) 
      {
        _conn.disconnect();
      }
    }
  }
}

Save Image and Text to SD card

//package com.android.viewer.imageprocessing;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;
import android.util.Log;

public class IOUtility {
  private static String mPrependFileName = "IMG_";
  private static final String TAG = "IOUtility";

  public static boolean saveImageToSDCard(Bitmap b, String appendFileName) {
    if (b != null) {
      try {
        File sdCardFile = Environment.getExternalStorageDirectory();
        if (sdCardFile.canWrite() == true) {
          File viewerFile = new File(sdCardFile, "Viewer");
          viewerFile.mkdirs();
          File imageFile = new File(viewerFile, mPrependFileName + appendFileName + ".png");
          FileOutputStream fileStream = new FileOutputStream(imageFile);
          b.compress(CompressFormat.PNG, 100, fileStream);
          fileStream.close();
        } else {
          Log.e(TAG, "IOUtility - Cannot write to SD Card");
        }
        return true;
      } catch (Exception e) {
        Log.e(TAG, "IOUtility - Error - " + e);
        e.printStackTrace();
      }
    }
    return false;
  }

  public static void setFilePrePend(String fileName) {
    Log.v(TAG, "IOUtility - Settings the prepended filename to: " + fileName);
    mPrependFileName = fileName;
  }

  public static boolean saveTextToSDCard(String content, String appendFileName) {
    try {
      File sdCardFile = Environment.getExternalStorageDirectory();
      if (sdCardFile.canWrite() == true) {
        File viewerFile = new File(sdCardFile, "Viewer");
        viewerFile.mkdirs();
        File textFile = new File(viewerFile, mPrependFileName + appendFileName);
        FileWriter fileWriter = new FileWriter(textFile);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        try {
          bufferedWriter.write(content);
        } finally {
          bufferedWriter.close();
        }
      } else {
        Log.e(TAG, "IOUtility - Cannot write to SD Card");
      }
      return true;
    } catch (Exception e) {
      Log.e(TAG, "IOUtility - Error [String empty string, depends on state] - " + e);
      e.printStackTrace();
    }
    return false;
  }

}
Scale and rotate Image
//package com.megagoodsoftware.MediaShare;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;

import java.util.Random;

/**
 * This class contains various utilities to manipulate Bitmaps. The methods of this class,
 * although static, are not thread safe and cannot be invoked by several threads at the
 * same time. Synchronization is required by the caller.
 */
final class ImageUtilities {
    private static final float PHOTO_BORDER_WIDTH = 3.0f;
    private static final int PHOTO_BORDER_COLOR = 0xffffffff;

    private static final float ROTATION_ANGLE_MIN = 2.5f;
    private static final float ROTATION_ANGLE_EXTRA = 5.5f;

    private static final Random sRandom = new Random();
    private static final Paint sPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
    private static final Paint sStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    static {
        sStrokePaint.setStrokeWidth(PHOTO_BORDER_WIDTH);
        sStrokePaint.setStyle(Paint.Style.STROKE);
        sStrokePaint.setColor(PHOTO_BORDER_COLOR);
    }

    /**
     * Rotate specified Bitmap by a random angle. The angle is either negative or positive,
     * and ranges, in degrees, from 2.5 to 8. After rotation a frame is overlaid on top
     * of the rotated image.
     *
     * This method is not thread safe.
     *
     * @param bitmap The Bitmap to rotate and apply a frame onto.
     *
     * @return A new Bitmap whose dimension are different from the original bitmap.
     */
    static Bitmap rotateAndFrame(Bitmap bitmap) {
        final boolean positive = sRandom.nextFloat() >= 0.5f;
        final float angle = (ROTATION_ANGLE_MIN + sRandom.nextFloat() * ROTATION_ANGLE_EXTRA) *
                (positive ? 1.0f : -1.0f);
        final double radAngle = Math.toRadians(angle);

        final int bitmapWidth = bitmap.getWidth();
        final int bitmapHeight = bitmap.getHeight();

        final double cosAngle = Math.abs(Math.cos(radAngle));
        final double sinAngle = Math.abs(Math.sin(radAngle));

        final int strokedWidth = (int) (bitmapWidth + 2 * PHOTO_BORDER_WIDTH);
        final int strokedHeight = (int) (bitmapHeight + 2 * PHOTO_BORDER_WIDTH);

        final int width = (int) (strokedHeight * sinAngle + strokedWidth * cosAngle);
        final int height = (int) (strokedWidth * sinAngle + strokedHeight * cosAngle);

        final float x = (width - bitmapWidth) / 2.0f;
        final float y = (height - bitmapHeight) / 2.0f;

        final Bitmap decored = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(decored);

        //canvas.rotate(angle, width / 2.0f, height / 2.0f);
        canvas.drawBitmap(bitmap, x, y, sPaint);
        canvas.drawRect(x, y, x + bitmapWidth, y + bitmapHeight, sStrokePaint);

        return decored;
    }

    /**
     * Scales the specified Bitmap to fit within the specified dimensions. After scaling,
     * a frame is overlaid on top of the scaled image.
     *
     * This method is not thread safe.
     *
     * @param bitmap The Bitmap to scale to fit the specified dimensions and to apply
     *               a frame onto.
     * @param width The maximum width of the new Bitmap.
     * @param height The maximum height of the new Bitmap.
     *
     * @return A scaled version of the original bitmap, whose dimension are less than or
     *         equal to the specified width and height.
     */
    static Bitmap scaleAndFrame(Bitmap bitmap, int width, int height) {
        final int bitmapWidth = bitmap.getWidth();
        final int bitmapHeight = bitmap.getHeight();

        final float scale = Math.min((float) width / (float) bitmapWidth, 
                (float) height / (float) bitmapHeight);

        final int scaledWidth = (int) (bitmapWidth * scale);
        final int scaledHeight = (int) (bitmapHeight * scale);

        final Bitmap decored = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
        final Canvas canvas = new Canvas(decored);

        final int offset = (int) (PHOTO_BORDER_WIDTH / 2);
        sStrokePaint.setAntiAlias(false);
        canvas.drawRect(offset, offset, scaledWidth - offset - 1,
                scaledHeight - offset - 1, sStrokePaint);
        sStrokePaint.setAntiAlias(true);

        return decored;

    }
}

create Image

   
//package com.anoshenko.android.mahjongg;

import java.util.Random;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

class Utils {

  public final static int DIE_COUNT = 36;

  private final static int DIE_FILL_COLOR    = 0xFFE0E0E0;
  private final static int DIE_BORDER_COLOR  = 0xFF808080;
  private final static int DIE_SIDE_COLOR    = 0xFFB0B0B0;
  private final static int DIE_ANGLE_COLOR  = 0xFFC0C0C0;

  //--------------------------------------------------------------------------
  static public Bitmap createDieImage(int width, int height, int wall_size) {
    Bitmap bitmap = Bitmap.createBitmap(width + wall_size, height + wall_size, Bitmap.Config.ARGB_8888);
    Canvas g = new Canvas(bitmap);
    Paint paint = new Paint();
    int right = width + wall_size - 1;
    int bottom = height + wall_size - 1;

    paint.setAntiAlias(false);
    paint.setStrokeWidth(1);

    g.drawARGB(0, 0, 0, 0);

    paint.setStyle(Paint.Style.FILL);
    paint.setColor(DIE_FILL_COLOR);
    g.drawRect(wall_size, 1, right, height, paint);

    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(DIE_ANGLE_COLOR);

    g.drawLine(wall_size-1, 1, wall_size-1, height, paint);
    g.drawLine(wall_size-1, height, right-1, height, paint);
    g.drawPoint(wall_size, 1, paint);
    g.drawPoint(wall_size, height-1, paint);
    g.drawPoint(right-1, 1, paint);
    g.drawPoint(right-1, height-1, paint);

    paint.setColor(DIE_SIDE_COLOR);

    for (int n=1; n<wall_size-1; n++) {
      g.drawLine(n, wall_size-n, n, bottom, paint);
      g.drawLine(1, bottom-n, right-wall_size+n, bottom-n, paint);
    }

    paint.setColor(DIE_BORDER_COLOR);

    g.drawLine(0, wall_size, 0, bottom, paint);
    g.drawLine(1, bottom, width, bottom, paint);

    g.drawLine(0, wall_size+1, wall_size+1, 0, paint);
    g.drawLine(width, bottom, right, height, paint);
    g.drawLine(1, bottom, wall_size, height, paint);
    g.drawLine(wall_size, 0, right, 0, paint);
    g.drawLine(right, 1, right, height, paint);

    return bitmap;
  }
}
Resize Photo

//package org.pluroid.pluroium;

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

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.preference.PreferenceManager;

class Utils {

    private static final String TAG = "Utils";
    
    private static final float MEDIUM_SIZE = 640.0f;    
    private static final float SMALL_SIZE = 240.0f;
    private static final int IO_BUFFER_SIZE = 4 * 1024;

    private static File getCacheDirectory(Context context, String dirname) {
        
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        boolean useExternal = false;
        File directory;

        if (useExternal && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            directory = Environment.getExternalStorageDirectory();
        } else {
            directory = context.getCacheDir();
        }

        File subdir = new File(directory, "pluroid");
        if (!subdir.exists()) {
            subdir.mkdirs();
        }

        return new File(subdir, dirname);
    }
    
    public static File ensureCache(Context context, String dirname) throws IOException {
        File cacheDirectory = getCacheDirectory(context, dirname);
        if (!cacheDirectory.exists()) {
            cacheDirectory.mkdirs();
            new File(cacheDirectory, ".nomedia").createNewFile();
        }   
        return cacheDirectory;
    }

    private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
     
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }
    
    public static File resizePhoto(Context context, String filePath, String resize) throws IOException {
        BitmapFactory.Options option;
        Bitmap originalBitmap, resizedBitmap;
        
        File cacheDirectory = getCacheDirectory(context, "images");
        if (!cacheDirectory.exists()) {
            cacheDirectory.mkdirs();
            new File(cacheDirectory, ".nomedia").createNewFile();
        }
        
        File newFilePath = new File(cacheDirectory, System.currentTimeMillis() + ".jpg");
        
        option = new BitmapFactory.Options();
        option.inJustDecodeBounds = true;
        originalBitmap = BitmapFactory.decodeFile(filePath, option);
        int w = option.outWidth, h = option.outHeight;
        int rw, rh;
        float newSize = "no".equals(resize) ? 0.0f : "medium".equals(resize) ? MEDIUM_SIZE : SMALL_SIZE;
        
        if (newSize == 0.0f) {
            FileInputStream fis = new FileInputStream(filePath);
            FileOutputStream fos = new FileOutputStream(newFilePath);
            copy(fis, fos);
            fis.close();
            fos.close();
            return newFilePath;
        } else {
            if (w > h && w >= newSize) {
                rw = (int) newSize;
                rh = (int) (h * newSize / w);
            } else if (h > w && h >= newSize) {
                rh = (int) newSize;
                rw = (int) (w * newSize / h);
            } else {
                rh = h;
                rw = w;
            }
            
            int scale = 1;
            while (true) {
                if (w / 2 < newSize || h / 2 < newSize) {
                    break;
                }
                w /= 2;
                h /= 2;
                scale++;
            }
            option = new BitmapFactory.Options();
            option.inSampleSize = scale - 1;
            originalBitmap = BitmapFactory.decodeFile(filePath, option);
            resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, rw, rh, true);
            
            FileOutputStream fos = new FileOutputStream(newFilePath);
            resizedBitmap.compress(CompressFormat.JPEG, 100, fos);
            fos.close();
            
            return newFilePath;
        }
    }
}