andrioid之BitmapUtil对图片处理代码demo
写了一个android对图片处理的类,贴出代码,大家学习下。
代码如下:(自己写的,非copy)
<span style="font-size:18px;">package com.tarena.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
/**工具类
* 该类作用是处理图片,将从服务端获取图片存到内存中
* */
public class BitmapUtil {
//该方法是从指定路径加载位图对象
public static Bitmap getbitmap(String path){
return BitmapFactory.decodeFile(path);
}
//按指定宽高比列加载位图到内存,传进来的图片数据时一个字节数组
public static Bitmap getBitmap(byte[] data,int width,int height){
//创建对象获取原始图片的宽高等信息
Options mOptions = new Options();
mOptions.inJustDecodeBounds=true;//此设置的意思是,读取原始图片的边界信息,即读取原图片的宽,高
//加载图片成为内存中的Bitmap对象
// BitmapFactory.decodeByteArray(data,0, data.length,mOptions);
//获取原始图片和想要得到的图片的宽高比列
int scalX=mOptions.outHeight/height;
int scalY=mOptions.outWidth/width;
mOptions.inSampleSize=scalX>scalY?scalX:scalY;//获取比列较大的缩放比例
mOptions.inJustDecodeBounds=false;//设置边界不可读
return BitmapFactory.decodeByteArray(data, 0, data.length, mOptions);//加载图片成为内存中的Bitmap
}
//保存图片到指定文件
public static void save(Bitmap bitmap,File file)throws FileNotFoundException,IOException{
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
if(!file.exists()){
file.createNewFile();
}
FileOutputStream out=new FileOutputStream(file);
//将位图写入文件
bitmap.compress(CompressFormat.JPEG, 100, out);
}
}
</span>
谢谢分享,学习,交流!
我走的很慢,但是我从没有后退!——林肯