Android BitmapUtils工具类
Bitmap工具类
public final class BitmapUtils {
public static final String TAG = "BitmapUtil";
private static int sShotScreenWidth = 480;
private static int sShotScreenHeight = 720;
private static int sShotScreenSize = sShotScreenWidth * sShotScreenHeight; @SuppressLint("StaticFieldLeak")
private static Context mContext;
@SuppressLint("StaticFieldLeak")
private static Activity mActivity; public void init(Context context,Activity ac) {
mContext=context;
mActivity=ac; DisplayMetrics dm = new DisplayMetrics();
ac.getWindowManager().getDefaultDisplay().getMetrics(dm);
//获取屏幕分辨率
sShotScreenWidth = dm.widthPixels;
sShotScreenHeight = dm.heightPixels;
sShotScreenSize = sShotScreenWidth * sShotScreenHeight;
} /**
* 图片合成
*
* @param bitmap 位图1
* @param mark 位图2
* @return Bitmap
*/
public static Bitmap createBitmap(Bitmap bitmap, Bitmap mark) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int mW = mark.getWidth();
int mH = mark.getHeight();
Bitmap newbitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);// 创建一个长宽一样的位图 Canvas cv = new Canvas(newbitmap);
cv.drawBitmap(bitmap, 0, 0, null);// 在 0,0坐标开始画入bitmap
cv.drawBitmap(mark, w - mW , h - mH , null);// 在右下角画入水印mark
cv.save(Canvas.ALL_SAVE_FLAG);// 保存
cv.restore();// 存储
return newbitmap;
} /**
* 放大缩小图片
* @param bitmap 位图
* @param w 新的宽度
* @param h 新的高度
* @return Bitmap
*/
public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidht = ((float) w / width);
float scaleHeight = ((float) h / height);
matrix.postScale(scaleWidht, scaleHeight);
return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
} /**
* 旋转图片
* @param bitmap 要旋转的图片
* @param angle 旋转角度
* @return bitmap
*/
public static Bitmap rotate(Bitmap bitmap,int angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
} /**
* 圆形图片
*@param source 位图
* @param strokeWidth 裁剪范围 0表示最大
* @param bl 是否需要描边
* @param bl 画笔粗细
* @param bl 颜色代码
* @return bitmap
*/
public static Bitmap createCircleBitmap(Bitmap source, int strokeWidth, boolean bl,int edge,int color) { int diameter = source.getWidth() < source.getHeight() ? source.getWidth() : source.getHeight();
Bitmap target = Bitmap.createBitmap(diameter, diameter, Config.ARGB_8888);
Canvas canvas = new Canvas(target);//创建画布 Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawCircle(diameter / 2, diameter / 2, diameter / 2, paint);//绘制圆形
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));//取相交裁剪
canvas.drawBitmap(source, strokeWidth, strokeWidth, paint);
if(bl) {
if (color == 0) color = 0xFFFEA248;//默认橘黄色
paint.setColor(color);
paint.setStyle(Paint.Style.STROKE);//描边
paint.setStrokeWidth(edge);
canvas.drawCircle(diameter / 2, diameter / 2, diameter / 2, paint);
}
return target;
} /**
* 圆角图片
* @param bitmap 位图
* @param rx x方向上的圆角半径
* @param ry y方向上的圆角半径
* @param bl 是否需要描边
* @param bl 画笔粗细
* @param bl 颜色代码
* @return bitmap
*/
public static Bitmap createCornerBitmap(Bitmap bitmap,int rx,int ry,boolean bl,int edge,int color) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);//创建画布 Paint paint = new Paint();
paint.setAntiAlias(true);
Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
RectF rectF = new RectF(rect);
canvas.drawRoundRect(rectF, rx, ry, paint);//绘制圆角矩形
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));//取相交裁剪
canvas.drawBitmap(bitmap, rect, rect, paint);
if(bl) {
if (color == 0) color = 0xFFFEA248;//默认橘黄色
paint.setColor(color);
paint.setColor(color);
paint.setStyle(Paint.Style.STROKE);//描边
paint.setStrokeWidth(edge);
canvas.drawRoundRect(rectF, rx, ry, paint);
}
return output;
} /**
* 按比例裁剪图片
* @param bitmap 位图
* @param wScale 裁剪宽 0~100%
* @param hScale 裁剪高 0~100%
* @return bitmap
*/
public static Bitmap cropBitmap(Bitmap bitmap, float wScale, float hScale) {
int w = bitmap.getWidth();
int h = bitmap.getHeight(); int wh = (int) (w * wScale);
int hw = (int) (h * hScale); int retX = (int) (w * (1 - wScale) / 2);
int retY = (int) (h * (1 - hScale) / 2); return Bitmap.createBitmap(bitmap, retX, retY, wh, hw, null, false);
} /**
* 获得带倒影的图片方法
* @param bitmap 位图
* @param region 倒影区域 0.1~1
* @return bitmap
*/
public static Bitmap createReflectionBitmap(Bitmap bitmap,float region) { int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.preScale(1, -1);//镜像缩放
Bitmap reflectionBitmap = Bitmap.createBitmap(
bitmap,0
, (int)(height*(1-region))//从哪个点开始绘制
, width
,(int) (height*region)//绘制多高
, matrix, false); Bitmap reflectionWithBitmap = Bitmap.createBitmap(width,height+ (int) (height*region),
Config.ARGB_8888);
Canvas canvas = new Canvas(reflectionWithBitmap);
canvas.drawBitmap(bitmap, 0, 0, null);
canvas.drawBitmap(reflectionBitmap, 0, height , null); LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
reflectionWithBitmap.getHeight()
, 0x70ffffff, 0x00ffffff, TileMode.CLAMP); Paint paint = new Paint();
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));//取两层绘制交集。显示下层。
canvas.drawRect(0, height, width, reflectionWithBitmap.getHeight() , paint);
return reflectionWithBitmap;
} /**
* 图片质量压缩
* @param bitmap
* @param many 百分比
* @return
*/
public static Bitmap compressBitmap(Bitmap bitmap, float many){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, (int)many*100, baos);
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
return BitmapFactory.decodeStream(isBm, null, null);
} /**
* 高级图片质量压缩
*@param bitmap 位图
* @param maxSize 压缩后的大小,单位kb
*/
public static Bitmap imageZoom(Bitmap bitmap, double maxSize) {
// 将bitmap放至数组中,意在获得bitmap的大小(与实际读取的原文件要大)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 格式、质量、输出流
bitmap.compress(Bitmap.CompressFormat.PNG, 70, baos);
byte[] b = baos.toByteArray();
// 将字节换成KB
double mid = b.length / 1024;
// 获取bitmap大小 是允许最大大小的多少倍
double i = mid / maxSize;
// 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
doRecycledIfNot(bitmap);
if (i > 1) {
// 缩放图片 此处用到平方根 将宽带和高度压缩掉对应的平方根倍
// (保持宽高不变,缩放后也达到了最大占用空间的大小)
return scaleWithWH(bitmap,bitmap.getWidth() / Math.sqrt(i),
bitmap.getHeight() / Math.sqrt(i));
}
return null;
} /***
* 图片缩放
*@param bitmap 位图
* @param w 新的宽度
* @param h 新的高度
* @return Bitmap
*/
public static Bitmap scaleWithWH(Bitmap bitmap, double w, double h) {
if (w == 0 || h == 0 || bitmap == null) {
return bitmap;
} else {
int width = bitmap.getWidth();
int height = bitmap.getHeight(); Matrix matrix = new Matrix();
float scaleWidth = (float) (w / width);
float scaleHeight = (float) (h / height); matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(bitmap, 0, 0, width, height,
matrix, true);
}
} /**
* YUV视频流格式转bitmap
* @param data YUV视频流格式
* @return width 设置宽度
* @return width 设置高度
*/
public static Bitmap getBitmap(byte[] data, int width, int height) {
Bitmap bitmap;
YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, width, height, null);
//data是onPreviewFrame参数提供
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0, yuvimage.getWidth(), yuvimage.getHeight()), 100, baos);//
// 80--JPG图片的质量[0-100],100最高
byte[] rawImage = baos.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
SoftReference<Bitmap> softRef = new SoftReference<Bitmap>(BitmapFactory.decodeByteArray(rawImage, 0, rawImage
.length, options));
bitmap = softRef.get();
return bitmap;
} /**
* 图片资源文件转bitmap
* @param file 图片的绝对路径
* @return bitmap
*/
public static Bitmap getBitmapResources(Context context,int resId){
return BitmapFactory.decodeResource(context.getResources(),resId);
} /**
* 将图片路径转Bitmap
* @Param path 图片路径
* @return Bitmap
*/
public static Bitmap getBitmapPath(String path){
return BitmapFactory.decodeFile(path);
} /**
* bitmap保存到指定路径
* @param file 图片的绝对路径
* @param file 位图
* @return bitmap
*/
public static boolean saveFile(String file, Bitmap bmp) {
if(TextUtils.isEmpty(file) || bmp == null) return false; File f = new File(file);
if (f.exists()) {
f.delete();
}else {
File p = f.getParentFile();
if(!p.exists()) {
p.mkdirs();
}
}
try {
FileOutputStream out = new FileOutputStream(f);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
} /**
* 回收一个未被回收的Bitmap
*@param bitmap
*/
public static void doRecycledIfNot(Bitmap bitmap) {
if (!bitmap.isRecycled()) {
bitmap.recycle();
}
}
/**
* 将图片转换成Base64编码的字符串
*/
public static String imageToBase64(String path){
if(TextUtils.isEmpty(path)){
return null;
}
InputStream is = null;
byte[] data = null;
String result = null;
try{
is = new FileInputStream(path);
//创建一个字符流大小的数组。
data = new byte[is.available()];
//写入数组
is.read(data);
//用默认的编码格式进行编码
result = Base64.encodeToString(data,Base64.DEFAULT);
}catch (Exception e){
e.printStackTrace();
}finally {
if(null !=is){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
return result;
}
}
修改图片的颜色
private Bitmap createRGBImage(Bitmap bitmap,int type) {
int bitmap_w = bitmap.getWidth();
int bitmap_h = bitmap.getHeight(); int[] arrayColor = new int[bitmap_w * bitmap_h];
int count = 0;
int color;
for (int i = 0; i < bitmap_h; i++) {
for (int j = 0; j < bitmap_w; j++) {
color = bitmap.getPixel(j, i);
if (color == -131073) {//颜色十进制值
arrayColor[count] = Color.TRANSPARENT;
}else{
arrayColor[count] = color;
}
count++;
}
}
bitmap = Bitmap.createBitmap(arrayColor, bitmap_w, bitmap_h, Bitmap.Config.ARGB_8888);
return bitmap;
}
Android BitmapUtils工具类的更多相关文章
- 53. Android常用工具类
主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.Prefer ...
- Android 常见工具类封装
1,MD5工具类: public class MD5Util { public final static String MD5(String s) { char hexDigits[] = { '0' ...
- 【转】Android常用工具类
主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.Prefe ...
- Android基础工具类重构系列一Toast
前言: 一直在考虑写一下Android实际项目中的一些总结,翻看CSDN博客,上一篇已经是一年多曾经. 本系列定位Android基础工具类重构.旨在记录实际项目中经经常使用到的一些工具类,比方Toas ...
- (转载)android 一些工具类汇总
android 一些工具类汇总 作者:曾田生z 字体:[增加 减小] 类型:转载 时间:2016-08-14我要评论 本文给大家汇总介绍了一些常用的Android工具类,非常的简单实用,有需要的小伙伴 ...
- 随笔分类 - Android之工具类
Android之文件搜索工具类 /** * @detail 搜索sdcard文件 * @param 需要进行文件搜索的目录 * @param 过滤搜索文件类型 */ private void sear ...
- Android 系统工具类SystemUtils
包含的功能有: 获取系统中所有APP应用.获取用户安装的APP应用.根据包名和Activity启动类查询应用信息.跳转到WIFI设置.WIFI网络开关.移动网络开关.GPS开关 当前若关则打开 当前若 ...
- Android Sqlite 工具类封装
鉴于经常使用 Sqlite 数据库做数据持久化处理,进行了一点封装,方便使用. 该封装类主要支持一下功能 支持多用户数据储存 支持 Sqlite数据库升级 支持传入 Sql 语句建表 支持 SQLit ...
- Android 常用工具类之SPUtil,可以修改默认sp文件的路径
参考: 1. 利用Java反射机制改变SharedPreferences存储路径 Singleton1900 2. Android快速开发系列 10个常用工具类 Hongyang import ...
随机推荐
- OpenStack-Ocata版+CentOS7.6 云平台环境搭建 —7.网络服务Neutron配置
网络服务Neutron本章节结束如何安装并配置网络服务(neutron)采用:ref:`provider networks <network1>`或:ref:`self-service n ...
- 【BJOI2019】删数 线段树
题目大意:一个数列若能在有限次数内删空,则称这个数列可以删空,一次删除操作定义如下: 记当前数列长度为$k$,则删掉数列中所有等于$k$的数. 现在有一个长度为$n$的数列$a$,有$m$次修改操作, ...
- [每天解决一问题系列 - 0013] 如何修改WiX Burn内置的窗口
问题描述: 我们产品的burn安装包仅支持.net 3.5 sp1以上,在只有.net 2.0的机器上会给用户弹一个窗口,告诉用户为什么不能够安装的原因.本来burn已经内置了,但是在日文操作系统下, ...
- canvas图片上传相关学习
今天主要是研究了canvas的关于图片上传的相关知识, context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);
- 线程的中断(Lock与synchronized)
Thread包含interrupt()方法,因此你可以终止被阻塞的任务,这个方法将设置线程的中断状态.如果一个线程已经被阻塞,或者试图执行一个阻塞操作.那么设置这个线程的中断状态将 抛出Interru ...
- CountDownLatch 和 CyclicBarrier 的基本使用
CountDownLatch 和 CyclicBarrier 是并发编程中常用的辅助类,两者使用上有点类似,但又有不同. 一.CountDownLatch CountDownLatch 可是实现类似计 ...
- 这是一位拿到BAT大厂offer应届生的年终总结,那么你的呢?
壹 关于求职 2018年初,我还在北京后厂村的马路上被风吹得瑟瑟发抖. 那时我刚刚结束了半年的实习时光,开始考虑年后是否要继续实习.一开始我也在纠结实习转正和秋招之间如何权衡,但是在经历了春招以后,我 ...
- dva reduxRouter 跳转路由的参数
应该由 新页面的 this.props.location获取
- nginx ngx_http_sub_module使用
ngx_http_sub_module模块是一个过滤器,它修改网站响应内容中的字符串,比如你想把响应内容中的‘iuwai’全部替换成‘aaaaa‘,这个模块已经内置在nginx中,但是默认未安装,需要 ...
- gbk转utf-8
1.文件转码:使用脚本 gbk转u8的脚本文件: #!/bin/bash FILE_SUFFIX="java xml html vm js" # FILE_SUFFIX=&qu ...