android为图片生成缩略图

android api里自带了一个Bitmap类,用于处理图片。不是很难,直接上代码

view plaincopy to clipboardprint?
package com.forwork.thumbnail;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
public class Thumbnail extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
saveMyBitmap("ooo");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void saveMyBitmap(String bitName) throws IOException {
File originalFile = new File("sdcard/pic/ll.jpg");
Bitmap bmp = decodeFile(originalFile);
File f = new File("/sdcard/" + bitName + ".jpg");
f.createNewFile();
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//BitmapFactory.Options options=new BitmapFactory.Options();
//options.inSampleSize = 10;
//options.inTempStorage = new byte[16*1024];
//Bitmap bmp = BitmapFactory.decodeFile("/sdcard/pic/sd.jpg");
//Bitmap bmp = BitmapFactory.decodeFile("/sdcard/pic/ll.jpg", options);
//bmp = Bitmap.createScaledBitmap(bmp, 800, 480, true);
bmp.compress(Bitmap.CompressFormat.JPEG, 30, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_HEIGHT=800;
final int REQUIRED_WIDTH=480;
//Find the correct scale value. It should be the power of 2.
int width_tmp=o.outWidth, height_tmp=o.outHeight;

System.out.println(width_tmp+" "+height_tmp);
Log.w("===", (width_tmp+" "+height_tmp));

int scale=1;
while(true){
if(width_tmp/2 break;
width_tmp/=2;
height_tmp/=2;
scale++;

Log.w("===", scale+"''"+width_tmp+" "+height_tmp);
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
}

你可能感兴趣的:(android为图片生成缩略图)