BitmapHelper

提供一些获取本地缩略图,获取网络图片。dp与px的相互转换等方法。

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.util.Base64; public class BitmapHelper { private static BitmapHelper util;
private static Context context = App.getInstance(); public static BitmapHelper getInstance() { if (util == null) {
util = new BitmapHelper(); }
return util; } private BitmapHelper() {
super();
} /**
* 将bitmap转为base64
*
* @param bitmap
* @param imgFormat
* @return
*/
@SuppressLint("NewApi")
public String bitmapToBase64(Bitmap bitmap, String imgFormat) { if (null == bitmap) { return null;
}
ByteArrayOutputStream out = null;
try {
out = new ByteArrayOutputStream();
Bitmap.CompressFormat compressFormat = Bitmap.CompressFormat.JPEG;
if (imgFormat.equalsIgnoreCase("png"))
compressFormat = Bitmap.CompressFormat.PNG;
bitmap.compress(compressFormat, 85, out);
out.flush();
out.close();
byte[] imgBytes = out.toByteArray();
return Base64.encodeToString(imgBytes, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
} /**
* 将图片转为base64
*
* @param imgPath
* @param imgFormat
* @return
*/
@SuppressLint("NewApi")
public String urlToBase64(String imgPath, String imgFormat) {
Bitmap bitmap = null;
if (imgPath != null && imgPath.length() > 0) {
bitmap = readBitmap(imgPath);
}
return bitmapToBase64(bitmap, imgFormat); } private Bitmap readBitmap(String imgPath) {
try {
return BitmapFactory.decodeFile(imgPath);
} catch (Exception e) {
return null;
}
} /**
* 得到圆角的bitmap
*
* @param bitmap
* @param corner
* 以长或宽的比例为半径,2表示二分之中的一个。8表示八分之中的一个
* @return
*/
public Bitmap getRoundedCornerBitmap(Bitmap bitmap, int corner) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float roundPx;
float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
if (width <= height) {
roundPx = width / corner;
top = 0;
bottom = width;
left = 0;
right = width;
height = width;
dst_left = 0;
dst_top = 0;
dst_right = width;
dst_bottom = width;
} else {
roundPx = height / corner;
float clip = (width - height) / corner;
left = clip;
right = width - clip;
top = 0;
bottom = height;
width = height;
dst_left = 0;
dst_top = 0;
dst_right = height;
dst_bottom = height;
}
Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect src = new Rect((int) left, (int) top, (int) right,
(int) bottom);
final Rect dst = new Rect((int) dst_left, (int) dst_top,
(int) dst_right, (int) dst_bottom);
final RectF rectF = new RectF(dst);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(
android.graphics.PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, src, dst, paint);
return output;
} /**
* 设置Bitmap圆角
*
* @param image
* 传入的Bitmap
* @param outerRadiusRat
* 圆角半径
* @return 返回处理后的Bitmap
*/
public Bitmap getRoundedBitmap(Bitmap image, int outerRadiusRat) {
int x = image.getWidth();
int y = image.getHeight();
// 依据源文件新建一个darwable对象
Drawable imageDrawable = new BitmapDrawable(image); // 新建一个新的输出图片
Bitmap output = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output); // 新建一个矩形
RectF outerRect = new RectF(0, 0, x, y); // 产生一个红色的圆角矩形
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.RED);
canvas.drawRoundRect(outerRect, outerRadiusRat, outerRadiusRat, paint); // 将源图片绘制到这个圆角矩形上
// 具体解释见http://lipeng88213.iteye.com/blog/1189452
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
imageDrawable.setBounds(0, 0, x, y);
canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);
imageDrawable.draw(canvas);
canvas.restore(); return output;
} /**
* 图片压缩
*
* @param image
* @return
*/
public Bitmap getCompressBitmap(Bitmap image, int minSize) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int options = 100;
while (baos.toByteArray().length / 1024 > minSize) {
options -= 10;
baos.reset();
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
return bitmap;
} /**
* 得到本地缩略图
*
* @param srcPath
* @return
*/
public Bitmap getCompressBitmapByLocal(String srcPath, int ww, int hh) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight; int be = 1;
if (w > h && w > ww) {
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return getCompressBitmap(bitmap, 100);
} /**
* 放大缩小图片
*
* @param bitmap
* @param w
* @param h
* @return
*/
public Bitmap getZoomBitmap(Bitmap bitmap, int w, int h) {
Bitmap newbmp = null;
if (bitmap != null) {
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);
newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,
true);
}
return newbmp;
} /**
* 得到网络图片
*
* @param imgUrl
* @return
*/
public Bitmap getHttpBitmap(String imgUrl) { Bitmap bitmap = null;
if (!PhoneHelper.getInstance().isNetworkConnected()) { return null;
} InputStream is = getHttpPicInputStream(imgUrl);
if (is != null) { bitmap = BitmapFactory.decodeStream(is); try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } return bitmap; } /**
* 得到网络图片的输入流
*
* @param url
* @return
*/
public InputStream getHttpPicInputStream(String url) {
InputStream is = null;
URL url1 = null;
try {
url1 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(30000);
conn.setRequestMethod("GET");
conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
is = conn.getInputStream();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} return is;
} /**
* Bitmap转化为drawable
*
* @param bitmap
* @return
*/
public Drawable bitmap2Drawable(Bitmap bitmap) {
return new BitmapDrawable(bitmap);
} /**
* Drawable 转 bitmap
*
* @param drawable
* @return
*/
public Bitmap drawable2Bitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
} else if (drawable instanceof NinePatchDrawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
} else {
return null;
}
} /**
* 将bitmap存为本地图片
* @param bitmap
* @param path
* @return
*/
public boolean saveBitmapForSdCard(Bitmap bitmap, String path) {
File f = new File(path);
File parent = new File(f.getParent());
FileOutputStream out = null;
if (!parent.exists()) {
parent.mkdirs();
}
try {
f.createNewFile();
out = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
out.flush();
out.close(); return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* dp转px
*
* @param context
* @param dpValue
* @return
*/
public int dp2Px(float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
} /**
* px转dp
*/
public int px2Dp(float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f);
} /**
* 依据网络状态获取本地图片缩略图
*
* @param picPath
* @return
*/
public Bitmap getBitmapByNetWork(String picPath) {
int networkType = PhoneHelper.getInstance().getNetType(); Bitmap tagBm = null;
ByteArrayOutputStream decodeBitmap = null;
int size = 100;
switch (networkType) {
case 1:
size = 150;
break;
case 2:
size = 80;
break;
case 3:
case 4:
size = 100;
break; default:
return null; }
decodeBitmap = getBitmapByteArray(picPath, size); if (decodeBitmap != null) {
byte[] array = decodeBitmap.toByteArray();
try {
tagBm = BitmapFactory.decodeByteArray(array, 0, array.length);
} catch (OutOfMemoryError oError) {
oError.printStackTrace();
} catch (Exception e) {
} } return tagBm; } /**
* 将本地图片转为输出流
* @param path
* @param size
* @return
*/
public ByteArrayOutputStream getBitmapByteArray(String path, int size) { BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;// 设置成了true,不占用内存,仅仅获取bitmap宽高
BitmapFactory.decodeFile(path, opts);
opts.inSampleSize = computeSampleSize(opts, -1, 1024 * 800); opts.inJustDecodeBounds = false;// 这里一定要将其设置回false,由于之前我们将其设置成了true
opts.inPurgeable = true;
opts.inInputShareable = true;
opts.inDither = false;
opts.inPurgeable = true;
opts.inPreferredConfig = Bitmap.Config.RGB_565;
opts.inTempStorage = new byte[100 * 1024];
FileInputStream is = null;
Bitmap bmp = null; ByteArrayOutputStream baos = null;
try {
is = new FileInputStream(path);
bmp = BitmapFactory.decodeFileDescriptor(is.getFD(), null, opts); baos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int options = 100;
while (baos.toByteArray().length / 1024 > size && options > 4) { // 循环推断假设压缩后图片是否大于100kb,大于继续压缩
baos.reset();// 重置baos即清空baos
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%。把压缩后的数据存放到baos中
options -= 2;// 每次都降低10
}
bmp.recycle();
return baos;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (OutOfMemoryError oError) {
oError.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (baos != null) {
baos.close();
} } catch (IOException e) {
e.printStackTrace();
}
System.gc();
}
return baos;
} /**
* 为了得到恰当的inSampleSize,Android提供了一种动态计算的方法
* @param options
* @param minSideLength
* @param maxNumOfPixels
* @return
*/
private int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength,
maxNumOfPixels); int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
} return roundedSize;
} private int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight; int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
Math.floor(w / minSideLength), Math.floor(h / minSideLength)); if (upperBound < lowerBound) {
return lowerBound;
} if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
} }

Bitmap工具类BitmapHelper的更多相关文章

  1. Bitmap工具类

    一直在使用的一个Bitmap工具类 处理Bitmap和ImageView对象,实现了下面功能: 1.saveBitmap: 把Bitmap对象持久存储到SD卡或手机内存. 2.getViewBitma ...

  2. Android BitmapUtils工具类

    Bitmap工具类 public final class BitmapUtils { public static final String TAG = "BitmapUtil"; ...

  3. Android-BitmapUtil工具类

    Bitmap工具类,获取Bitmap对象 public class BitmapUtil { private BitmapUtil(){} /** * 根据资源id获取指定大小的Bitmap对象 * ...

  4. Android Bitmap与DrawAble与byte[]与InputStream之间的转换工具类【转】

    package com.soai.imdemo; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; ...

  5. Android开发之常用必备工具类图片bitmap转成字符串string与String字符串转换为bitmap图片格式

    作者:程序员小冰,CSDN博客:http://blog.csdn.net/qq_21376985 QQ986945193 博客园主页:http://www.cnblogs.com/mcxiaobing ...

  6. java工具类

    1.HttpUtilsHttp网络工具类,主要包括httpGet.httpPost以及http参数相关方法,以httpGet为例:static HttpResponse httpGet(HttpReq ...

  7. 随笔分类 - Android之工具类

    Android之文件搜索工具类 /** * @detail 搜索sdcard文件 * @param 需要进行文件搜索的目录 * @param 过滤搜索文件类型 */ private void sear ...

  8. Android 系统工具类SystemUtils

    包含的功能有: 获取系统中所有APP应用.获取用户安装的APP应用.根据包名和Activity启动类查询应用信息.跳转到WIFI设置.WIFI网络开关.移动网络开关.GPS开关 当前若关则打开 当前若 ...

  9. 转:工具类之SpannableStringUtils(相信你会爱上它)

    这个工具类真是构思了良久才设计出来,采用了建造者模式,然后你们就可以用链式调用了,talk is cheap, let me show the demo. demo code 有没有心动一下哈,下面就 ...

随机推荐

  1. 总结esp8266刷Python的完整的步骤(终极总结)

    2018-04-0319:12:02 从玩microPython 到现在,一路荆棘一路坎坷. 不知道只有我遇到这样的问题还是microPython太不稳定,还是我买的板子太糙.总之遇到了太多问题了. ...

  2. springboot运行模式

    1.springboot项目常见的运行方式:  2.说明: idea:在开发环境中跑项目,也就是我们在编码过程中的用的做多的方式 jar.war:线上.服务器上执行jar.war包的方式 maven插 ...

  3. NoSQL与关系数据库

    关系型数据库:完全支持关系代数理论作为基础:有较大的数据规模:固定的数据库模式:查询效率快:强一致性:数据完整性较易实现:扩展性一般:可用性好. NoSQL:部分支持关系代数理论作为基础:有超大数据规 ...

  4. 【笔记JS/HTML/CSS】web中的HTTP协议(1)

    最近都在coursera刷课,加上自己课业也忙起来了,总是忘记写学习笔记ORZ 自省ing... 在写HTML的时候,form表单需要通过HTTP协议向服务器提交.查询数据(如下图) 客户端通过HTT ...

  5. HDU_1166_敌兵布阵

    敌兵布阵 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submis ...

  6. day21-1 类的继承

    目录 类的继承 什么是继承 为什么用继承 对象的继承 继承与抽象 继承的应用 对象属性查找顺序 类的继承 什么是继承 继承是一种创建新类的方式,新建的类可以继承一个或多个父类(python支持多继承) ...

  7. Mkdocs在html网页上看markdown

    目录 Mkdocs在html网页上看markdown 1. 本文目的 2. Mkdocs介绍 3. DEMO的演示 3.1 配置需求 3.2 安装mkdocs 3.3 新建工程 3.4 启动服务器 3 ...

  8. Python之list、tuple、dict、set

    参考原文 廖雪峰Python PS:来看看Python中比较特殊的几种数据类型list.tuple.dict.set list list(列表)是Python内置的一种数据类型,它是一种有序.可变的集 ...

  9. xmpp之配置Xcode(1)

    介绍 ios上的XMPPFramework你能够在Xcode/iPhoneXMPP 目录找到,它只是实现了XMPP的一小部分功能. 下面主要介绍在开发XMPPFramework ios应用之前的配置工 ...

  10. Opencv下双线性插值法进行图像放缩

    关于图像放缩的算法有很多,本文主要介绍双线性插值法进行图像放缩,本文参考了: http://www.cnblogs.com/funny-world/p/3162003.html 我们设源图像src的大 ...