package com.example.administrator.filemanager.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
/**
* Created by Administrator on 2016/12/30.
*/
public class BitmapUtil {
/**
* 图片路径为字符串格式时
*/
public static Bitmap loadBitmap(String pathName,SizeMessage sizeMessage){
//获取图片大小
int imgWeight=sizeMessage.getWidth();
int imgHeight=sizeMessage.getHeight();
Context context=sizeMessage.getContext();
//图像处理
Options options=new Options();
options.inJustDecodeBounds=true;//打开图片边缘
BitmapFactory.decodeFile(pathName,options);
int imgW = options.outWidth;//处理后拿到的宽
int imgH = options.outHeight;//处理后拿到的高
if (imgW <= imgWeight && imgH<=imgHeight){
//设置加载图片时的比例
options.inSampleSize = 1;
}else{
//按比例计算宽高
int scaleW = imgW/imgWeight;
int scaleH = imgH/imgHeight;
//比较大小
int scale = scaleW > scaleH ? scaleW:scaleH;
//按比例加载资源
options.inSampleSize = scale;
}
options.inJustDecodeBounds = false;//关闭图片边缘
Bitmap bitmap = BitmapFactory.decodeFile(pathName,options);
return bitmap;
}
/**
* 图片路径为int类型时
*/
public static Bitmap loadBitmap(int redId,SizeMessage sizeMessage) {
//获取图片大小
int intweight=sizeMessage.getWidth();
int intheight=sizeMessage.getHeight();
Context context=sizeMessage.getContext();
//图像处理
Options options=new Options();
options.inJustDecodeBounds = true;//打开图片边缘 拿到信息;
BitmapFactory.decodeResource(context.getResources(),redId,options);
int imgW = options.outWidth;//处理后拿到的宽
int imgH = options.outHeight;//处理后拿到的高
if (imgW <= intweight && imgH<=intheight){
//设置加载图片时的比例
options.inSampleSize = 1;
}else{
//按比例计算宽高
int scaleW = imgW/intweight;
int scaleH = imgH/intheight;
//比较大小
int scale = scaleW > scaleH ? scaleW:scaleH;
//按比例加载资源
options.inSampleSize = scale;
}
options.inJustDecodeBounds = false;//关闭图片边缘
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),redId,options);
return bitmap;
}
/**
* 内部类
*/
public static class SizeMessage{
private Context context;
private int width;
private int height;
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public SizeMessage(Context context,boolean isPX, int width, int height) {
this.context = context;
if(!isPX){//如果不是,转换成像素格式
width=DeviceUtil.dp2px(context,width);
height=DeviceUtil.dp2px(context,height);
}
this.width = width;
this.height = height;
}
}
}
相关文章
- 12-29验证码图片工具类
- 12-29SqlSession获取的工具类(简单配置)
- 12-29excel转图片工具类
- 12-29获取IP地址工具类
- 12-295. JDBC工具类的抽取 - 封装获取连接、关闭资源
- 12-29工具类CTools实现字符编码转换和获取当前路径
- 12-29Calendar工具类获取月初和月末时间
- 12-29Spring Aop中,获取被代理类的工具
- 12-29根据经度纬度获取距离(km/m)等工具类
- 12-29请求ip获取工具类