package com.m520it.www.androidimagetest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;
import java.io.BufferedOutputStream;
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 java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
/**
- @author 乔石
- @time 2016/8/20 19:33
- @desc ${TODD}
*/
public class ImageUtil {
// 这是安卓当中处理图片的一个工具类
public static Bitmap compassBitmap(Bitmap bitmap, int size) {
/*实现图片压缩的到固指定大小内的一个方法*/
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩发100代表没有进行压缩
int options = 100;
while (baos.toByteArray().length / 1024 > size) {
//判断当前的图片是否否和压缩的标准大小 不符合继续压缩
baos.reset();//清空
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里是压缩到options% 将压缩后的数据放置到baos里面
options -= 5;//每次压缩质量渐5
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(baos.toByteArray());//将压缩后得到的数据放置到响应的输入流里面
//生成想要的大小的图片并且返回
Bitmap bitmap1 = BitmapFactory.decodeStream(inputStream, null, null);
return bitmap1;
}
public Bitmap covertGeryImg(Bitmap img, int redsize, int greensize, int bluesize) {
/*根据红绿蓝所占的比例合理的构建一张灰度的图像*/
int width = img.getWidth();//获取到位图的宽和高
int height = img.getHeight();
/*通过位图的大小我们需要创建像素点的数组*/
int[] pixels = new int[width * height];
img.getPixels(pixels, 0, width, 0, 0, width, height);//pixels是用来接收的数组 0开始写到数组的啥位置 第三个值必须大于或者等于width 开始读的位置 读多少行和列
int alpha = 0xFF << 24;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int grey = pixels[width * i + j];
int red = ((grey & 0x00ff0000) >> 16);
int green = ((grey & 0x00ff0000) >> 8);
int blue = ((grey & 0x00ff0000));
grey = (int) ((float) red * redsize + (float) green * greensize + (float) blue * bluesize);
grey = alpha | (grey << 16) | (grey << 8) | grey;//构建了一个32位的图像 透明度是8位 红绿蓝的话各占8位
pixels[width * i + j] = grey;
}
}
Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
return result;
}
public Bitmap getMirrorImage(Bitmap image_src, int mirrorType) {
/*实现了水平镜像 垂直镜像 90度 180度 270度 360度的旋转*/
final int VeticalMirror = 1;
final int HroitalMirror = 2;
final int RotationMirror90 = 3;
final int RotationMirror180 = 4;
final int RotationMirror270 = 5;
final int RotationMirror360 = 6;
int width = image_src.getWidth();
int height = image_src.getHeight();
Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas cv = new Canvas(result);
Matrix matrix = new Matrix();
switch (mirrorType) {
case VeticalMirror:
matrix.postScale(1, -1);
break;
case HroitalMirror:
matrix.postScale(-1, 1);
break;
case RotationMirror90:
matrix.postRotate(90);
break;
case RotationMirror180:
matrix.postRotate(180);
break;
case RotationMirror270:
matrix.postRotate(270);
break;
case RotationMirror360:
matrix.postRotate(360);
break;
default:
break;
}
Bitmap newbitmap = Bitmap.createBitmap(image_src, 0, 0, width, height, matrix, true);
cv.drawBitmap(newbitmap, new Rect(0, 0, newbitmap.getWidth(), newbitmap.getHeight()), new Rect(0, 0, width, height), null);
return result;
}
public Bitmap getScaleBitmapByUrl(String url, int width, int height) {
/*通过URL生成图片并且按照一定的要求进行缩放*/
/*通过url获取生成位图*/
URL mFileUrl = null;
Bitmap bitmap = null;
try {
mFileUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) mFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream inputStream = conn.getInputStream();
Bitmap bitmap1 = BitmapFactory.decodeStream(inputStream);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
/*对相应的位图进行缩放*/
int getwidth = bitmap.getWidth();
int getheight = bitmap.getHeight();
float scalewidth = ((float) getwidth / width);
float scaleheight = ((float) getheight / height);
Matrix matrix = new Matrix();
matrix.postScale(scalewidth, scaleheight);
//生成新的位图
Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
return resizeBitmap;
}
public static Bitmap getBitmaopFromSrc(Context context,int bitAdress){
//方便实现从资源文件中加载图片的方法
Bitmap bitmap=null;
bitmap=BitmapFactory.decodeResource(context.getResources(),bitAdress);
return bitmap;
}
public final void cuteImage(Canvas cav, Paint paint,Bitmap imgBit,int x,
int y,int w,int h,int line,int row){
/*从图片中截取其中的一部分为一个新的图片*/
cav.clipRect(x,y,x+2,y+h);
cav.drawBitmap(imgBit,x-line*w,y-row*h,paint);
cav.restore();
}
public static Bitmap setImageAlpha(Bitmap sourceImg,int number){
/*获取到指定的透明度的图片*/
int[] argb=new int[sourceImg.getWidth()*sourceImg.getHeight()];
sourceImg.getPixels(argb,0,sourceImg.getWidth(),0,0,sourceImg.getWidth(),sourceImg.getHeight());//获取源图片的像素存储到指定的数组里面里
number=number*255/100;
for (int i=0;i<argb.length;i++){
argb[i]=((number << 24)|(argb[i] & 0x00FFFFFF));//修改最高两位的值 因为最高两位就是透明度
}
sourceImg=Bitmap.createBitmap(argb,sourceImg.getWidth(),sourceImg.getHeight(), Bitmap.Config.ARGB_8888);
return sourceImg;
}
public static Bitmap getRoundConerBitmap(Bitmap bitmap,float roundPx){
/*传入一张位图图像 并且传入圆角的半径的大小 构建一张圆角的图片*/
Bitmap output=Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas cav=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);
paint.setAntiAlias(true);//设置刚锯齿的一种方式
cav.drawARGB(0,0,0,0);
paint.setColor(color);
cav.drawRoundRect(rectf,roundPx,roundPx,paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
cav.drawBitmap(bitmap,rect,rect,paint);
return output;
}
public static Bitmap createRefelctionBitmapWithOriginBitmap(Bitmap bitmap){
/传入位图图像 构建倒影/
final int reflectionGap=4;
int width=bitmap.getWidth();
int height=bitmap.getHeight();
Matrix matrix=new Matrix();//构建我们的变换变换矩阵
matrix.preScale(1,-1);
Bitmap reflectionImage=Bitmap.createBitmap(bitmap,0,height/2,width,height/2,matrix,false);
Bitmap bitmapWithReflection=Bitmap.createBitmap(width,(height+height/2), Bitmap.Config.ARGB_8888);
Canvas cav=new Canvas(bitmapWithReflection);
cav.drawBitmap(bitmap,0,0,null);
Paint defaultPaint=new Paint();
cav.drawRect(0,height,width,height+reflectionGap,defaultPaint);
cav.drawBitmap(reflectionImage,0,height+reflectionGap,null);
Paint paint=new Paint();
LinearGradient shader=new LinearGradient(0,bitmap.getHeight(),0,bitmap.getHeight()+reflectionGap,0x70ffffff,0x00ffffff, Shader.TileMode.CLAMP);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
cav.drawRect(0,height,width,bitmapWithReflection.getHeight()+reflectionGap,paint);
return bitmapWithReflection;
}
private Bitmap createWaterMaskImage(Context getContext,Bitmap src,Bitmap watermark){
/*利用原图和水印标志生成水印图片*/
if(src==null) {
return null;
}
int width=src.getWidth();
int height=src.getHeight();
int markwidth=watermark.getWidth();
int markheight=watermark.getHeight();
Bitmap newbitmap=Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);//创建新的位图图像用来承载要返回的位图
Canvas cv=new Canvas(newbitmap);
//将原图画入新的位图图像当中
cv.drawBitmap(src,0,0,null);
//在新位图图像的右下角画入水印图像标志
cv.drawBitmap(watermark,20,20,null);
cv.save(Canvas.ALL_SAVE_FLAG);
cv.restore();
return newbitmap;
}
public Bitmap drwaTextToBitmap(Context gcontext,int gResId,String gText){
/*为我们的图片添加文字水印*/
Resources resources = gcontext.getResources();
float density = resources.getDisplayMetrics().density;
Bitmap bitmap=BitmapFactory.decodeResource(resources,gResId);
Matrix matrix=new Matrix();
matrix.postScale(300*density,300*density);
Bitmap newbitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
Canvas cav=new Canvas(bitmap);
Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);//消除锯齿
paint.setColor(Color.RED);
paint.setTextSize((int)(18*density));
paint.setDither(true);//获取清晰的图片采样
paint.setFilterBitmap(true);//过滤一些
Rect bounds=new Rect();
paint.getTextBounds(gText,0,gText.length(),bounds);
int x=30;int y=30;
cav.drawText(gText,x*density,y*density,paint);
return bitmap;
}
/--------------------------------------调用系统的相机或者相册获取图片--------------------------------/
public static void getImageFormAlbum(Activity ac,int actionCode){
// //利用Intent调用系统的相册
// Intent intent=new Intent(Intent.ACTION_PICK);
// intent.setType("image/");//相片类型
// ac.startActivityForResult(intent,actionCode);
}
public static void openCamer(Activity ac,int actionCode){
// /开启相机*/
//
// //Intent getImageByCamera = new Intent(“Android.media.action.IMAGE_CAPTURE”); 获取高清大图时候使用
// ac.startActivityForResult(getImageByCamera,actionCode);
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
// Intent getImageByCamera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//获取保存的路径
//给成员变量赋值
File sdDir=null;
boolean sdCardExist=Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if(sdCardExist) {
sdDir=Environment.getExternalStorageDirectory();
}
String capturePath = sdDir + "/" + System.currentTimeMillis() + ".jpg";
if (!sdDir.exists()) {
sdDir.mkdirs();
}
getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(capturePath)));
getImageByCamera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
ac.startActivityForResult(getImageByCamera, actionCode);
} else {
Toast.makeText(ac.getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
}
}
/**
* 获取存储路径,可以写在FileUtils中
*/
public String getSDPath() {
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
if (sdCardExist) {
sdDir = Environment.getExternalStorageDirectory();//获取跟目录
}
return sdDir.toString();
}
public static void doActivityResult(Activity ac,int requestcode,int resultCode,Intent data,String spath) {
//拿去从相机返回的相片
Uri uri=data.getData();
if(uri==null) {
Bundle bundle=data.getExtras();
if(bundle!=null) {
Bitmap photo=(Bitmap) bundle.get("data");
saveImage(photo,spath);
}else {
Toast.makeText(ac.getApplicationContext(), "err", Toast.LENGTH_SHORT).show();
}
}
}
public static boolean saveImage(Bitmap bitmap,String spath){
try {
/*将获取到的图片保存在指定的位置*/
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(spath,false));
bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/--------------------------------------调用系统的相机或者相册获取图片--------------------------------/
public static Bitmap getCircleImage(Bitmap resource,int min){
/*该方法传入一张普通图片 生成一张固定大小的 原形图片*/
final Paint paint=new Paint();
paint.setAntiAlias(true);//设置抗锯齿的效果
Bitmap target=Bitmap.createBitmap(min,min, Bitmap.Config.ARGB_8888);
/*产生一个同样大小的画布*/
Canvas cav=new Canvas(target);
/*首先绘制原形*/
cav.drawCircle(min/2,min/2,min/2,paint);
/*设置SRC_IN模式*/
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
/*绘制图片*/
cav.drawBitmap(resource,0,0,paint);
return target;
}
public Bitmap add2Bitmap(Bitmap first, ArrayList<Bitmap> Bitmaps) {
/*实现多张图片的顺序拼接图片实现拼接*/
int width =first.getWidth();
int height = first.getHeight();
for(int i=0;i<Bitmaps.size();i++){
width+=Bitmaps.get(i).getWidth();
height=Math.max(height,Bitmaps.get(i).getHeight());
}
Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
canvas.drawBitmap(first, 0, 0, null);
int startwidth=first.getWidth();
for (int i=0;i<Bitmaps.size();i++){
canvas.drawBitmap(Bitmaps.get(i), startwidth, 0, null);
startwidth+=Bitmaps.get(i).getWidth();
}
return result;
}
}
网友评论