Bitmap 篇
2016-05-24 13:41
239 查看
关于bitmap 网上有太多的操作方法,这里收集了一些(比较杂),有需要的盆友可以根据需要再次封装。
import java.io.BufferedOutputStream; 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.sql.Timestamp; import java.text.SimpleDateFormat; import android.R.dimen; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.PorterDuff; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader.TileMode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.media.Image; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.MediaStore; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.ImageView.ScaleType; /** * 图片操作工具包 */ public class BitmapUtilities { public final static String SDCARD_MNT = "/mnt/sdcard"; public final static String SDCARD = "/sdcard"; /** * 写图片文件 在Android系统中,文件保存在 /data/data/PACKAGE_NAME/files 目录下 * * @throws IOException */ public static void saveImage(Context context, String fileName, Bitmap bitmap) throws IOException { saveImage(context, fileName, bitmap, 100); } public static void saveImage(Context context, String fileName, Bitmap bitmap, int quality) throws IOException { if (bitmap == null || fileName == null || context == null) return; FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.JPEG, quality, stream); byte[] bytes = stream.toByteArray(); fos.write(bytes); fos.close(); } /** * 获取图片大小 * <br> * 在Android API(12)之前的版本和后来的版本是不一样 * @param bitmap * @return */ public int getBitmapSize(Bitmap bitmap){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){ //API 19 return bitmap.getAllocationByteCount(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1){//API 12 return bitmap.getByteCount(); } return bitmap.getRowBytes() * bitmap.getHeight(); //earlier version } /** * convert Bitmap to byte array * * @param b * @return */ public static byte[] bitmapToByte(Bitmap b) { if (b == null) { return null; } ByteArrayOutputStream o = new ByteArrayOutputStream(); b.compress(Bitmap.CompressFormat.PNG, 100, o); return o.toByteArray(); } /** * convert Drawable to byte array * * @param d * @return */ public static byte[] drawableToByte(Drawable d) { return bitmapToByte(drawableToBitmap(d)); } /** * convert byte array to Drawable * * @param b * @return */ public static Drawable byteToDrawable(byte[] b) { return bitmapToDrawable(byteToBitmap(b)); } /** * convert byte array to Bitmap * * @param b * @return */ public static Bitmap byteToBitmap(byte[] b) { return (b == null || b.length == 0) ? null : BitmapFactory.decodeByteArray(b, 0, b.length); } /** * 写图片文件到SD卡 * * @throws IOException */ public static void saveImageToSD(Context ctx, String filePath, Bitmap bitmap, int quality) throws IOException { if (bitmap != null) { File file = new File(filePath.substring(0, filePath.lastIndexOf(File.separator))); if (!file.exists()) { file.mkdirs(); } BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(filePath)); bitmap.compress(CompressFormat.JPEG, quality, bos); bos.flush(); bos.close(); if(ctx!=null){ scanPhoto(ctx, filePath); } } } /** * 让Gallery上能马上看到该图片 */ private static void scanPhoto(Context ctx, String imgFileName) { Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); File file = new File(imgFileName); Uri contentUri = Uri.fromFile(file); mediaScanIntent.setData(contentUri); ctx.sendBroadcast(mediaScanIntent); } /** * 图片去色,返回黑白的图片 * @param old * @return */ public static Bitmap getGreyImage(Bitmap old) { int width, height; height = old.getHeight(); width = old.getWidth(); Bitmap newbitmap= Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); Canvas c = new Canvas(old); Paint paint = new Paint(); ColorMatrix cm = new ColorMatrix(); cm.setSaturation(0); ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm); paint.setColorFilter(f); c.drawBitmap(newbitmap, 0, 0, paint); return newbitmap; } /** * 获取bitmap * * @param context * @param fileName * @return */ public static Bitmap getBitmap(Context context, String fileName) { FileInputStream fis = null; Bitmap bitmap = null; try { fis = context.openFileInput(fileName); bitmap = BitmapFactory.decodeStream(fis); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } finally { try { fis.close(); } catch (Exception e) { } } return bitmap; } /** * 获取bitmap * * @param filePath * @return */ public static Bitmap getBitmapByPath(String filePath) { return getBitmapByPath(filePath, null); } public static Bitmap getBitmapByPath(String filePath, BitmapFactory.Options opts) { FileInputStream fis = null; Bitmap bitmap = null; try { File file = new File(filePath); fis = new FileInputStream(file); bitmap = BitmapFactory.decodeStream(fis, null, opts); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } finally { try { fis.close(); } catch (Exception e) { } } return bitmap; } /** * 获取bitmap * * @param file * @return */ public static Bitmap getBitmapByFile(File file) { FileInputStream fis = null; Bitmap bitmap = null; try { fis = new FileInputStream(file); bitmap = BitmapFactory.decodeStream(fis); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } finally { try { fis.close(); } catch (Exception e) { } } return bitmap; } /** * 图片透明度处理 * * @param sourceImg * 原始图片 * @param number (0-100) * 透明度 * @return */ public static Bitmap getTransparentBitmap(Bitmap sourceImg, int number){ int[] argb = new int[sourceImg.getWidth() * sourceImg.getHeight()]; sourceImg.getPixels(argb, 0, sourceImg.getWidth(), 0, 0, sourceImg .getWidth(), sourceImg.getHeight());// 获得图片的ARGB值 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(), Config.ARGB_8888); return sourceImg; } /** * 通过canvas改变bitmap 透明度 * @param canvas * @param context * @param bitmapid * @param transparency 透明值 (0-255) */ public static void SetTransByCanvas(Canvas canvas,Context context,int bitmapid,int transparency){ // 取得Resource 图片的Bitmap Bitmap vBitmap = BitmapFactory.decodeResource( context.getResources() , bitmapid ); // 建立Paint 物件 Paint vPaint = new Paint(); vPaint .setStyle( Paint.Style.STROKE ); //空心 vPaint .setAlpha(transparency); // //canvas.drawBitmap ( vBitmap , 50, 100, null ); //无透明 canvas.drawBitmap ( vBitmap , 50, 200, vPaint ); //有透明 } /*** * 绘制带有边框的文字 * * @param strMsg * :绘制内容 * @param g * :画布 * @param paint * :画笔 * @param setx * ::X轴起始坐标 * @param sety * :Y轴的起始坐标 * @param fg * :前景色 * @param bg * :背景色 */ public void drawText(String strMsg, Canvas g, Paint paint, int setx, int sety, int fg, int bg) { paint.setColor(bg); g.drawText(strMsg, setx + 1, sety, paint); g.drawText(strMsg, setx, sety -1, paint); g.drawText(strMsg, setx, sety + 1, paint); g.drawText(strMsg, setx -1, sety, paint); paint.setColor(fg); g.drawText(strMsg, setx, sety, paint); g.restore(); } /*** * 图片分割 图片平均分割方法,将大图平均分割为N行N列,方便用户使用 * * @param g * :画布 * @param paint * :画笔 * @param imgBit * :图片 * @param x * :X轴起点坐标 * @param y * :Y轴起点坐标 * @param w * :单一图片的宽度 * @param h * :单一图片的高度 * @param line * :第几列 * @param row * :第几行 */ public final void cuteImage(Canvas g, Paint paint, Bitmap imgBit, int x, int y, int w, int h, int line, int row) { g.clipRect(x, y, x + w, h + y); g.drawBitmap(imgBit, x - line * w, y - row * h, paint); g.restore(); } /** * 根据一张大图,返回切割后的图元数组 * @param resourseId:资源id * @param row:总行数 * @param col:总列数 * multiple:图片缩放的倍数1:表示不变,2表示放大为原来的2倍 * @return */ public static Bitmap[] getBitmaps(Context context,int resourseId,int row,int col,float multiple) { Bitmap bitmaps[] = new Bitmap[row*col]; Bitmap source = decodeResource(context, resourseId); int temp = 0; for(int i=1; i<=row; i++) { for(int j=1; j<=col; j++) { bitmaps[temp] = getImage(context,source, i, j, row, col,multiple,false); temp ++; } } if(source != null && !source.isRecycled()) { source.recycle(); source = null; } return bitmaps; } /** * 从大图中截取小图 * @param r * @param resourseId * @param row * @param col * @param rowTotal * @param colTotal * @return */ private static Bitmap getImage(Context context,Bitmap source,int row,int col, int rowTotal, int colTotal, float multiple,boolean isRecycle) { Bitmap temp = Bitmap.createBitmap(source, (col-1)*source.getWidth()/colTotal, (row-1)*source.getHeight()/rowTotal, source.getWidth()/colTotal, source.getHeight()/rowTotal); if(isRecycle) { if(source != null && !source.isRecycled()) { source.recycle(); source = null; } } if(multiple != 1.0) { Matrix matrix = new Matrix(); matrix.postScale(multiple, multiple); temp = Bitmap.createBitmap(temp, 0, 0,temp.getWidth(), temp.getHeight(), matrix, true); } return temp; } /** * 通过id加载bitmap * @param context * @param resourseId * @return */ public static Bitmap decodeResource(Context context,int resourseId) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.ARGB_8888; opt.inPurgeable = true; opt.inInputShareable = true; //需把 inPurgeable设置为true,否则被忽略 //获取资源图片 InputStream is = context.getResources().openRawResource(resourseId); return BitmapFactory.decodeStream(is,null,opt); //decodeStream直接调用JNI>>nativeDecodeAsset()来完成decode,无需再使用java层的createBitmap,从而节省了java层的空间 } /** * 从assets文件下解析图片 * @param resName * @return */ public static Bitmap decodeBitmapFromAssets(Context context,String resName) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; options.inPurgeable = true; options.inInputShareable = true; InputStream in = null; try { //in = AssetsResourcesUtil.openResource(resName); in =context.getAssets().open(resName); } catch (IOException e) { e.printStackTrace(); } return BitmapFactory.decodeStream(in, null, options); } /*** * 加载本地图片 图片加载方法,方便用户加载图片 * @param context:主运行函数实例 * @param bitAdress:图片地址,一般指向R下的drawable目录 * @return */ public final Bitmap CreatImage(Context context, int bitAdress) { Bitmap bitmaptemp = null; bitmaptemp = BitmapFactory.decodeResource(context.getResources(), bitAdress); return bitmaptemp; } /** * 使用当前时间戳拼接一个唯一的文件名 * * @param format * @return */ public static String getTempFileName() { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SS"); String fileName = format.format(new Timestamp(System .currentTimeMillis())); return fileName; } /** * 获取照相机使用的目录 * * @return */ public static String getCamerPath() { return Environment.getExternalStorageDirectory() + File.separator + "FounderNews" + File.separator; } /** * 判断当前Url是否标准的content://样式,如果不是,则返回绝对路径 * * @param uri * @return */ public static String getAbsolutePathFromNoStandardUri(Uri mUri) { String filePath = null; String mUriString = mUri.toString(); mUriString = Uri.decode(mUriString); String pre1 = "file://" + SDCARD + File.separator; String pre2 = "file://" + SDCARD_MNT + File.separator; if (mUriString.startsWith(pre1)) { filePath = Environment.getExternalStorageDirectory().getPath() + File.separator + mUriString.substring(pre1.length()); } else if (mUriString.startsWith(pre2)) { filePath = Environment.getExternalStorageDirectory().getPath() + File.separator + mUriString.substring(pre2.length()); } return filePath; } /** * 通过uri获取文件的绝对路径 * * @param uri * @return */ public static String getAbsoluteImagePath(Activity context, Uri uri) { String imagePath = ""; String[] proj = { MediaStore.Images.Media.DATA }; @SuppressWarnings("deprecation") Cursor cursor = context.managedQuery(uri, proj, // Which columns to // return null, // WHERE clause; which rows to return (all rows) null, // WHERE clause selection arguments (none) null); // Order-by clause (ascending by name) if (cursor != null) { int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); if (cursor.getCount() > 0 && cursor.moveToFirst()) { imagePath = cursor.getString(column_index); } } return imagePath; } /** * 获取图片缩略图 只有Android2.1以上版本支持 * * @param imgName * @param kind * MediaStore.Images.Thumbnails.MICRO_KIND * @return */ /* public static Bitmap loadImgThumbnail(Activity context, String imgName, int kind) { Bitmap bitmap = null; String[] proj = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME }; Cursor cursor = context.managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj, MediaStore.Images.Media.DISPLAY_NAME + "='" + imgName + "'", null, null); if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) { ContentResolver crThumb = context.getContentResolver(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 1; bitmap = MethodsCompat.getThumbnail(crThumb, cursor.getInt(0), kind, options); } return bitmap; } public static Bitmap loadImgThumbnail(String filePath, int w, int h) { Bitmap bitmap = getBitmapByPath(filePath); return zoomBitmap(bitmap, w, h); } */ /** * 获取SD卡中最新图片路径(用于查找最新图片) * * @return */ @SuppressWarnings("unused") public static String getLatestImage(Activity context) { String latestImage = null; String[] items = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA }; @SuppressWarnings("deprecation") Cursor cursor = context.managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, items, null, null, MediaStore.Images.Media._ID + " desc"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor .moveToNext()) { latestImage = cursor.getString(1); break; } } return latestImage; } /** * 计算缩放图片的宽高 * * @param img_size * @param square_size * @return */ public static int[] scaleImageSize(int[] img_size, int square_size) { if (img_size[0] <= square_size && img_size[1] <= square_size) return img_size; double ratio = square_size / (double) Math.max(img_size[0], img_size[1]); return new int[] { (int) (img_size[0] * ratio), (int) (img_size[1] * ratio) }; } /** * 创建缩略图 * * @param context * @param largeImagePath * 原始大图路径 * @param thumbfilePath * 输出缩略图路径 * @param square_size * 输出图片宽度 * @param quality * 输出图片质量(0-100) * @throws IOException */ public static void createImageThumbnail(Context context, String largeImagePath, String thumbfilePath, int square_size, int quality) throws IOException { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inSampleSize = 1; // 原始图片bitmap Bitmap cur_bitmap = getBitmapByPath(largeImagePath, opts); if (cur_bitmap == null) return; // 原始图片的高宽 int[] cur_img_size = new int[] { cur_bitmap.getWidth(), cur_bitmap.getHeight() }; // 计算原始图片缩放后的宽高 int[] new_img_size = scaleImageSize(cur_img_size, square_size); // 生成缩放后的bitmap Bitmap thb_bitmap = zoomBitmap(cur_bitmap, new_img_size[0], new_img_size[1]); // 生成缩放后的图片文件 saveImageToSD(null,thumbfilePath, thb_bitmap, quality); } /** * 放大缩小图片 * * @param bitmap * @param w * @param h * @return */ public static Bitmap zoomBitmap(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 bitmap * @param Mwidth * @param Mheight * @param angle 旋转角度 * @return */ public static Bitmap scaleBitmap(Bitmap bitmap,int Mwidth,int Mheight,int angle) { // 获取这个图片的宽和高 int width = bitmap.getWidth(); int height = bitmap.getHeight(); // 定义预转换成的图片的宽度和高度 int newWidth = Mwidth; int newHeight = Mheight; // 计算缩放率,新尺寸除原始尺寸 float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // 创建操作图片用的matrix对象 Matrix matrix = new Matrix(); // 缩放图片动作 matrix.postScale(scaleWidth, scaleHeight); // 旋转图片 动作 matrix.postRotate(angle); // 创建新的图片 Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); return resizedBitmap; } /** * (缩放)根据手机界面宽高来重绘图片 * * @param context * Activity * @param bitmap * @return */ public static Bitmap reDrawBitMap(Activity context, Bitmap bitmap) { DisplayMetrics dm = new DisplayMetrics(); context.getWindowManager().getDefaultDisplay().getMetrics(dm); int rHeight = dm.heightPixels; int rWidth = dm.widthPixels; // float rHeight=dm.heightPixels/dm.density+0.5f; // float rWidth=dm.widthPixels/dm.density+0.5f; // int height=bitmap.getScaledHeight(dm); // int width = bitmap.getScaledWidth(dm); int height = bitmap.getHeight(); int width = bitmap.getWidth(); float zoomScale; /** 方式1 **/ // if(rWidth/rHeight>width/height){//以高为准 // zoomScale=((float) rHeight) / height; // }else{ // //if(rWidth/rHeight<width/height)//以宽为准 // zoomScale=((float) rWidth) / width; // } /** 方式2 **/ // if(width*1.5 >= height) {//以宽为准 // if(width >= rWidth) // zoomScale = ((float) rWidth) / width; // else // zoomScale = 1.0f; // }else {//以高为准 // if(height >= rHeight) // zoomScale = ((float) rHeight) / height; // else // zoomScale = 1.0f; // } /** 方式3 **/ if (width >= rWidth) zoomScale = ((float) rWidth) / width; else zoomScale = 1.0f; // 创建操作图片用的matrix对象 Matrix matrix = new Matrix(); // 缩放图片动作 matrix.postScale(zoomScale, zoomScale); Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); return resizedBitmap; } /** * 将Drawable转化为Bitmap * * @param drawable * @return */ public static Bitmap drawableToBitmap(Drawable drawable) { int width = drawable.getIntrinsicWidth(); int height = drawable.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, drawable .getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, width, height); drawable.draw(canvas); return bitmap; } /** * 将bitmap转化为drawable * * @param bitmap * @return */ public static Drawable bitmapToDrawable(Bitmap bitmap) { Drawable drawable = new BitmapDrawable(bitmap); return drawable; } /** * 获得圆角图片的方法 * * @param bitmap * @param roundPx * 一般设成14 * @return */ public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) { 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); 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); return output; } /** * 获得带倒影的图片方法 * * @param bitmap * @return */ public static Bitmap createReflectionImageWithOrigin(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), Config.ARGB_8888); Canvas canvas = new Canvas(bitmapWithReflection); canvas.drawBitmap(bitmap, 0, 0, null); Paint deafalutPaint = new Paint(); canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint); canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); Paint paint = new Paint(); LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP); paint.setShader(shader); // Set the Transfer mode to be porter duff and destination in paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); // Draw a rectangle using the paint with our linear gradient canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint); return bitmapWithReflection; } /** * 获取图片类型 * * @param file * @return */ public static String getImageType(File file) { if (file == null || !file.exists()) { return null; } InputStream in = null; try { in = new FileInputStream(file); String type = getImageType(in); return type; } catch (IOException e) { return null; } finally { try { if (in != null) { in.close(); } } catch (IOException e) { } } } /** * 获取图片的类型信息 * * @param in * @return * @see #getImageType(byte[]) */ public static String getImageType(InputStream in) { if (in == null) { return null; } try { byte[] bytes = new byte[8]; in.read(bytes); return getImageType(bytes); } catch (IOException e) { return null; } } /** * 获取图片的类型信息(jpg png ...) * * @param bytes * 2~8 byte at beginning of the image file * @return image mimetype or null if the file is not image */ public static String getImageType(byte[] bytes) { if (isJPEG(bytes)) { return "image/jpeg"; } if (isGIF(bytes)) { return "image/gif"; } if (isPNG(bytes)) { return "image/png"; } if (isBMP(bytes)) { return "application/x-bmp"; } return null; } private static boolean isJPEG(byte[] b) { if (b.length < 2) { return false; } return (b[0] == (byte) 0xFF) && (b[1] == (byte) 0xD8); } private static boolean isGIF(byte[] b) { if (b.length < 6) { return false; } return b[0] == 'G' && b[1] == 'I' && b[2] == 'F' && b[3] == '8' && (b[4] == '7' || b[4] == '9') && b[5] == 'a'; } private static boolean isPNG(byte[] b) { if (b.length < 8) { return false; } return (b[0] == (byte) 137 && b[1] == (byte) 80 && b[2] == (byte) 78 && b[3] == (byte) 71 && b[4] == (byte) 13 && b[5] == (byte) 10 && b[6] == (byte) 26 && b[7] == (byte) 10); } private static boolean isBMP(byte[] b) { if (b.length < 2) { return false; } return (b[0] == 0x42) && (b[1] == 0x4d); } /** * create the bitmap from a byte array * 生成水印图片 * @param src the bitmap object you want proecss * @param watermark the water mark above the src (水印标志的图片) * @return return a bitmap object ,if paramter's length is 0,return null */ public static Bitmap createBitmap( Bitmap src,Bitmap watermark ) { String tag = "createBitmap"; // Log.d( tag, "create a new bitmap" ); if( src == null ) { return null; } int w = src.getWidth(); int h = src.getHeight(); int ww = watermark.getWidth(); int wh = watermark.getHeight(); //create the new blank bitmap Bitmap newb = Bitmap.createBitmap( w, h, Config.ARGB_8888 );//创建一个新的和SRC长度宽度一样的位图 Canvas cv = new Canvas( newb ); //draw src into cv.drawBitmap( src, 0, 0, null );//在 0,0坐标开始画入src //draw watermark into cv.drawBitmap( watermark, w - ww + 5, h - wh + 5, null );//在src的右下角画入水印 //save all clip cv.save( Canvas.ALL_SAVE_FLAG );//保存 //store cv.restore();//存储 return newb; } /** 重新编码Bitmap * * @param src * 需要重新编码的Bitmap * * @param format * 编码后的格式(目前只支持png和jpeg这两种格式) * * @param quality * 重新生成后的bitmap的质量 * * @return * 返回重新生成后的bitmap */ private static Bitmap codec(Bitmap src, Bitmap.CompressFormat format, int quality) { ByteArrayOutputStream os = new ByteArrayOutputStream(); src.compress(format, quality, os); byte[] array = os.toByteArray(); return BitmapFactory.decodeByteArray(array, 0, array.length); } /** * Stream转换成Byte * @param is * @return */ static byte[] streamToBytes(InputStream is) { ByteArrayOutputStream os = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024]; int len; try { while ((len = is.read(buffer)) >= 0) { os.write(buffer, 0, len); } } catch (java.io.IOException e) { } return os.toByteArray(); } /** * 把一个View的对象转换成bitmap * @param view 对象 */ static Bitmap getViewBitmap(View v) { v.clearFocus(); v.setPressed(false); //能画缓存就返回false boolean willNotCache = v.willNotCacheDrawing(); v.setWillNotCacheDrawing(false); int color = v.getDrawingCacheBackgroundColor(); v.setDrawingCacheBackgroundColor(0); if (color != 0) { v.destroyDrawingCache(); } v.buildDrawingCache(); Bitmap cacheBitmap = v.getDrawingCache(); if (cacheBitmap == null) { //Log.e(TAG, "failed getViewBitmap(" + v + ")", new RuntimeException()); return null; } Bitmap bitmap = Bitmap.createBitmap(cacheBitmap); // Restore the view v.destroyDrawingCache(); v.setWillNotCacheDrawing(willNotCache); v.setDrawingCacheBackgroundColor(color); return bitmap; } /** * 圆形头像 * @param bitmap * @param Myheadportrait */ public static void SetCircleBitmap(Bitmap bitmap, ImageView Myheadportrait) { /* Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_4444); int width=bitmap.getWidth(); int height=bitmap.getHeight(); // int squareWidth=Math.min(width,height); Canvas canvas = new Canvas(output); final Paint paint = new Paint(); final Rect rect = new Rect(0, 0,width,height); final RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); canvas.drawRoundRect(rectF,width,height, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); Myheadportrait.setImageBitmap(output); Myheadportrait.setScaleType(ScaleType.FIT_XY);*/ int width=bitmap.getWidth(); int height=bitmap.getHeight(); int diameter=Math.min(width,height); Bitmap backgroundBMP=Bitmap.createBitmap(diameter, diameter, Config.ARGB_4444); Canvas canvas=new Canvas(backgroundBMP); Paint paint=new Paint(); paint.setAntiAlias(true);//设置边缘光滑 canvas.drawARGB(0, 0, 0, 0);//以颜色ARBG填充整个控件的Canvas背景 Rect rect=new Rect(0, 0,diameter,diameter); RectF rectF=new RectF(0,0,diameter,diameter);//图片矩形 canvas.drawCircle(diameter/2, diameter/2, diameter/2, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect,rectF, paint); Myheadportrait.setImageBitmap(bitmap); Myheadportrait.setScaleType(ScaleType.FIT_XY); // http://407827531.iteye.com/blog/1470519 // 1.PorterDuff.Mode.CLEAR // 所绘制不会提交到画布上。 // 2.PorterDuff.Mode.SRC // 显示上层绘制图片 // 3.PorterDuff.Mode.DST // 显示下层绘制图片 // 4.PorterDuff.Mode.SRC_OVER // 正常绘制显示,上下层绘制叠盖。 // 5.PorterDuff.Mode.DST_OVER // 上下层都显示。下层居上显示。 // 6.PorterDuff.Mode.SRC_IN // 取两层绘制交集。显示上层。 // 7.PorterDuff.Mode.DST_IN // 取两层绘制交集。显示下层。 // 8.PorterDuff.Mode.SRC_OUT // 取上层绘制非交集部分。 // 9.PorterDuff.Mode.DST_OUT // 取下层绘制非交集部分。 // 10.PorterDuff.Mode.SRC_ATOP // 取下层非交集部分与上层交集部分 // 11.PorterDuff.Mode.DST_ATOP // 取上层非交集部分与下层交集部分 // 12.PorterDuff.Mode.XOR // 中间隐藏 显示其余的 // 13.PorterDuff.Mode.DARKEN // 中间交汇处加深 // 14.PorterDuff.Mode.LIGHTEN // 显示中间交汇处 隐藏其余 // 15.PorterDuff.Mode.MULTIPLY // // 16.PorterDuff.Mode.SCREEN } /* //Android Matrix类实现镜像方法 public void drawRegion(Image image_src, int x_src, int y_src, int width, int height, int transform, int x_dest, int y_dest, int anchor){ if((anchor&VCENTER) != 0){ y_dest -= height/2; }else if((anchor&BOTTOM) != 0){ y_dest -= height; } if((anchor&RIGHT) != 0){ x_dest -= width; }else if((anchor&HCENTER) != 0){ x_dest -= width/2; } Bitmap newMap = Bitmap.createBitmap(image_src.getBitmap(), x_src, y_src, width, height); Matrix mMatrix = new Matrix(); Matrix temp = new Matrix(); Matrix temp2 = new Matrix(); float[] mirrorY = { -1, 0, 0, 0, 1, 0, 0, 0, 1 }; temp.setValues(mirrorY); switch(transform){ case Sprite.TRANS_NONE: break; case Sprite.TRANS_ROT90: mMatrix.setRotate(90,width/2, height/2); break; case Sprite.TRANS_ROT180: mMatrix.setRotate(180,width/2, height/2); break; case Sprite.TRANS_ROT270: mMatrix.setRotate(270,width/2, height/2); break; case Sprite.TRANS_MIRROR: mMatrix.postConcat(temp); break; case Sprite.TRANS_MIRROR_ROT90: mMatrix.postConcat(temp); mMatrix.setRotate(90,width/2, height/2); break; case Sprite.TRANS_MIRROR_ROT180: mMatrix.postConcat(temp); mMatrix.setRotate(180,width/2, height/2); break; case Sprite.TRANS_MIRROR_ROT270: mMatrix.postConcat(temp); mMatrix.setRotate(270,width/2, height/2); break; } mMatrix.setTranslate(x_dest, y_dest); canvas.drawBitmap(newMap, mMatrix, mPaint); } */ }
相关文章推荐
- 如何利用BI实现人力资源可视化管理
- PAT乙级—1042. 字符统计(20)-native
- 如何利用BI实现人力资源可视化管理
- qt介绍
- AEAI ESB路由转换机制说明
- IOS9 UIStackView(转)
- MPI实用命令
- .Net版行号消除器
- 递归和迭代算法 [汉诺塔问题]
- 快速排序
- cookie
- 面试必备-快速排序
- shell ${} 用法
- Android OpenGL_ES2.0 Frustum 我能看见哪些地方?
- 网络摄像头实时获取信息
- 跨平台的C++应用和UI开发库 QT
- 跨平台的C++应用和UI开发库 QT
- H5项目常见问题汇总及解决方案
- ngrok 反向代理配置,把内网映射出去
- Android的jni测试