3 Star 3 Fork 1

zhang dongling / Android_Util_Class

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
ImageUtil 14.35 KB
一键复制 编辑 原始数据 按行查看 历史
zhang dongling 提交于 2015-09-18 15:57 . 添加图片处理
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom2.Content;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
public class ImageUtil {
/**
* 解码位图文件,并设置合适的高度和宽度
*
* @param filename
* 文件路径
* @param reqWidth
* 目标宽度
* @param reqHeight
* 目标高度
* @return A bitmap sampled down from the original with the same aspect
* ratio and dimensions that are equal to or greater than the
* requested width and height
*/
public static Bitmap decodeSampledBitmapFromFile(String filename, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.ARGB_4444;
options.inDither = true;// 抖动
options.inPurgeable = true;
options.inInputShareable = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize 计算inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filename, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
// 图像的高和宽
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
// 计算高、宽比例
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee a final image
// with both dimensions larger than or equal to the requested height
// and width.
// 选择的最小比率为inSampleSize值,这将保证最终的图像大于或等于目标高度和宽度
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger
// inSampleSize).
// 这提供了一些额外的逻辑情况下,图像有一个奇怪的纵横比。
// 例如,全景图可以有一个更大的宽度大于高度。在这种情况下,
// 总像素可能最终仍然过大,以适应舒适的内存,所以我们应该更积极的样品下来的图像(大inSampleSize ) 。
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down
// further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
/**
* 按质量压缩图片,此方法耗CPU
*
* @param image
* 源图像
* @param targetSize
* 目标大小
* @return
*/
private static Bitmap compressImage(Bitmap image, int targetSize) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 100;
while (baos.toByteArray().length / 1024 > targetSize) { // 循环判断如果压缩后图片是否大于目标大小,大于继续压缩
baos.reset();// 重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
options -= 10;// 每次都减少10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
isBm = null;
baos = null;
return bitmap;
}
/**
* 双重压缩
*
* @param filename
* @param reqWidth
* @param reqHeight
* @param targetSize
* @return
*/
public static Bitmap doubleCompress(String filename, int reqWidth, int reqHeight, int targetSize) {
return compressImage(decodeSampledBitmapFromFile(filename, reqWidth, reqHeight), targetSize);
}
/**
* 保存图片
*
* @param bitName
* //处理后保存的文件名称
* @param mBitmap
* //要处理的图片
* @throws IOException
*/
public static void saveMyBitmap(Context context, String bitName, Bitmap mBitmap) throws IOException {
String path = BaseConfig.getValue(context, "picDir", "");
String fn = bitName.substring(0, bitName.indexOf("."));// 只截取文件名称
File f = new File(path + fn + "-s.JPG");
f.createNewFile();
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mBitmap = Bitmap.createScaledBitmap(mBitmap, 250, 150, true);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 将Drawable转换成Bitmap
*
* @param draw
* @return
*/
public static Bitmap DrawableToBitmap(Drawable draw, int bW, int bH) {
Bitmap bitmap = Bitmap.createBitmap(bW, bH,
draw.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
// canvas.setBitmap(bitmap);
draw.setBounds(0, 0, bW, bH);
draw.draw(canvas);
return bitmap;
}
/**
* bitmap转 byte数组
*
* @param bm
* @return
*/
public static byte[] Bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
/**
* 获取圆形图片
*
* @param bitmap
* @param pixels
* @return
*/
public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
setBitmapBorder(canvas, 6);// 默认边框6像素
return output;
}
/**
* 给bitmap设置边框 6
*
* @param canvas
*/
private static void setBitmapBorder(Canvas canvas, int strokeWidth) {
Rect rect = canvas.getClipBounds();
Paint paint = new Paint();
paint.setAntiAlias(true);
rect.bottom = rect.bottom - strokeWidth;
rect.right = rect.right - strokeWidth;
// 设置边框颜色
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
// 设置边框宽度
paint.setStrokeWidth(strokeWidth);
canvas.drawCircle(rect.width() / 2 + strokeWidth / 2, rect.width() / 2 + strokeWidth / 2, rect.width() / 2,
paint);
}
/**
* 压缩图片到指定的大小
* @param bitmap
* @return
*/
private static Bitmap small(Bitmap bitmap,float width) {
Matrix matrix = new Matrix();
matrix.postScale(width/bitmap.getWidth(),width/bitmap.getHeight()); //长和宽放大缩小的比例
Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
return resizeBmp;
}
// 头像获得200*200的图片
public static Bitmap roundWihte(Bitmap bitmap) {
return small(bitmap,200f);
}
// 分享的头像图片
public static Bitmap shareHeadImage(Resources res,String imageURL,int levelRes,String name,String levelStr,String zhishu,float width,String fenShu,String gaoYu,String pingJia,String qwdfStr) {
Log.e(ShareImageBitmapUtils.class.getName(), imageURL+","+ name+","+ levelStr+","+zhishu+","+fenShu+","+gaoYu+","+pingJia+","+qwdfStr);
//创建背景图片
Bitmap bitmap=BitmapFactory.decodeResource(res, R.drawable.shareimg_bg).copy(Bitmap.Config.ARGB_8888, true);
// Bitmap bitmap = Bitmap.createBitmap(480, 800, Bitmap.Config.RGB_565); // 按指定参数创建一个空的Bitmap对象
Canvas canvas = new Canvas(bitmap);
final Paint paint = new Paint();
paint.setAntiAlias(true);
//画头像
Bitmap header=null;
if (imageURL!=null&&imageURL.length()>1) {
/**
* 加上一个对本地缓存的查找
*/
String bitmapName = imageURL.substring(imageURL.lastIndexOf("/") + 1);
File cacheDir = new File(Constants.TEMP_FILE_PATH);
File[] cacheFiles = cacheDir.listFiles();
int i = 0;
if (null != cacheFiles) {
for (; i < cacheFiles.length; i++) {
if (bitmapName.equals(cacheFiles[i].getName())) {
break;
}
}
if (i < cacheFiles.length) {
header= BitmapFactory.decodeFile(Constants.TEMP_FILE_PATH+ bitmapName);
}
}
}
if (header==null) {
header=BitmapFactory.decodeResource(res, R.drawable.default_avatar).copy(Bitmap.Config.ARGB_8888, true);
}
Typeface fontFace = Typeface.createFromAsset(res.getAssets(),"fonts/Walkway_SemiBold.ttf");
//画指定图片到指定的位置
canvas.drawBitmap(small(toRoundCorner(header, header.getWidth()/2),150f), 240, 80, null);//画头像
//画名称
Paint namePaint=new Paint();
namePaint.setAntiAlias(true);
namePaint.setTypeface(fontFace);
namePaint.setTextSize(20);
namePaint.setStyle(Paint.Style.FILL);
namePaint.setColor(0xff646464);
float nameWidth=namePaint.measureText(name);//名称的宽度
canvas.drawText(name, width/2f-nameWidth/2f, 275, namePaint);//画名称
canvas.drawText(levelStr, 295, 320, namePaint);//画人气等级
canvas.drawText(zhishu, 435, 320, namePaint);//画指数
float gyW=namePaint.measureText(gaoYu);
canvas.drawText(gaoYu,width/2f-gyW/2f , 470, namePaint);//画高于多少好友百分比
//画等级图片
Bitmap levelBt=BitmapFactory.decodeResource(res,levelRes);//copy(Bitmap.Config.ARGB_8888, true)
canvas.drawBitmap(small(levelBt,60), 155, 370, null);//画等级图片
//画分数
Paint fenshuPaint=new Paint();
fenshuPaint.setAntiAlias(true);
fenshuPaint.setTypeface(fontFace);
fenshuPaint.setStyle(Paint.Style.FILL);
fenshuPaint.setTextSize(100);
fenshuPaint.setColor(0xff7e7e7e);
// fenshuPaint.setColor(Color.RED);
canvas.drawText(fenShu, 240, 430, fenshuPaint);//画分数
//画评价
Paint pjPaint=new Paint();
pjPaint.setStyle(Paint.Style.FILL);
pjPaint.setTypeface(Typeface.DEFAULT_BOLD);
pjPaint.setAntiAlias(true);
pjPaint.setTextSize(24);
fenshuPaint.setColor(Color.parseColor("#2e2e2e"));
// pjPaint.setColor(0x666666);
float pjW=pjPaint.measureText(pingJia);
canvas.drawText(pingJia, width/2f-pjW/2f, 550, pjPaint);//画评价
//画全网得分
Paint qwdfPaint=new Paint();
qwdfPaint.setAntiAlias(true);
qwdfPaint.setStyle(Paint.Style.FILL);
qwdfPaint.setTypeface(fontFace);
qwdfPaint.setTextSize(80);
qwdfPaint.setColor(Color.parseColor("#323232"));
float qwdfW=qwdfPaint.measureText(qwdfStr);
canvas.drawText(qwdfStr, width/2f-qwdfW/2f, 740, qwdfPaint);//画全网得分
return bitmap;
}
/***
* 保存bmp到本地文件中
* @param bmp bitmap 图像
* @param newName 文件压缩后需要保存的新路径
*/
public static String SaveBitmap(Bitmap bmp,String dirs,String newName) {
if (TextUtils.isEmpty(newName)) {
return null;
}
if (dirs!=null) {
File dirFiles=new File(dirs);
if (!dirFiles.exists()) {
dirFiles.mkdirs();
}
}
File pic = new File(dirs+"/"+newName);
Log.e(ShareImageBitmapUtils.class.getName(), "pic="+pic.getAbsolutePath());
try {
if (!pic.exists()) {
pic.createNewFile();
}else{
pic.delete();
pic.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(pic);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return pic.getPath();
}
/*------------------------------分享图片生成--------------------------------*/
/**
* 生成分享的图片
* @param res
* @param imageURL 头像的地址-如果为null 默认头像
* @param levelRes 等级图片id
* @param name 名称
* @param levelStr 等级字符串 例如V1
* @param zhishu指数
* @param fenShu分数
* @param gaoYu高于描述例如:高于您86%的好友
* @param pingJia评价
* @param qwdfStr全网排名
* @return
*/
public static String getShareLocalImagePaht(Resources res,String imageURL,int levelRes,String name,String levelStr,String zhishu,String fenShu,String gaoYu,String pingJia,String qwdfStr){
Log.e(ShareImageBitmapUtils.class.getName(), imageURL+","+ name+","+ levelStr+","+zhishu+","+fenShu+","+gaoYu+","+pingJia+","+qwdfStr);
String rootPaht=Environment.getExternalStorageDirectory().getAbsolutePath();
//获取背景图片生成的bmp
Bitmap bmp=shareHeadImage(res, imageURL, levelRes, name, levelStr, zhishu, 640, fenShu, gaoYu, pingJia, qwdfStr);
//保存到本地,获取图片路径
String path=SaveBitmap(bmp, rootPaht, "shareimg.png");
File file=new File(path);
if (file.exists()) {
return path;
}else{
return null;
}
}
}
Android
1
https://gitee.com/jason/Android_Util_Class.git
git@gitee.com:jason/Android_Util_Class.git
jason
Android_Util_Class
Android_Util_Class
master

搜索帮助