/** * Bitmap工具類 * 建立Bitmap對象 */ public class BitmapUtils{ private Context context; /** * 單例模式建立實體類 */ public BitmapUtils (Context context){ } /** * 壓縮後圖片 */ public Bitmap BitmapCompression(Bitmap rawBitmap, float newHeight, float newWidth){ // 獲得原圖的高度和寬度 float rawHeight = rawBitmap.getHight(); float rawWidth = rawBitmap.getWidth(); // 計算縮放因子 float heightScale = ((float) newHeight) / rawHeight; float widthScale = ((float) newWidth) / rawWidth; // 新創建矩陣 Matrix matrix = new Matrix(); matrix.postScale(heightScale, widthScale); // 設置圖片的旋轉角度 //matrix.postRotate(-30); // 設置圖片的傾斜 //matrix.postSkew(0.1f, 0.1f); //壓縮後圖片的寬和高以及KB大小均會變化 returned Bitmap.createBitmap(rawBitmap, 0, 0, rawWidth, rawWidth, matrix, true); } /** * 將Bitmap轉換成Drawable並在ImageView上顯示 */ public void BitmapToDrawable(Bitmap rawBitmap, ImageView imageView){ Drawable newBitmapDrawable = new BitmapDrawable(rawBitmap); imageView.setImageDrawable(newBitmapDrawable); } //問題: //原圖大小爲625x690 90.2kB //若是設置圖片500x500 壓縮後大小爲171kB.即壓縮後kB反而變大了. //緣由是將:compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream); //第二個參數quality設置得有些大了(好比100). //經常使用的是80,剛設100太大了形成的. //————>以上爲將圖片高寬和的大小kB壓縮 /** * 壓縮且保存圖片到SDCard * Bitmap rawBitmap 須要保存的Bitmap * String fileName 保存的文件名 * int quality 圖像壓縮比的值 */ private void compressAndSaveBitmapToSDCard(Bitmap rawBitmap, String fileName, int quality){ String saveFilePaht = this.getSDCardPath() + File.separator + fileName; File saveFile = new File(saveFilePaht); if (!saveFile.exists()) { try { saveFile.createNewFile(); FileOutputStream fileOutputStream=new FileOutputStream(saveFile); if (fileOutputStream!=null) { //imageBitmap.compress(format, quality, stream); //把位圖的壓縮信息寫入到一個指定的輸出流中 //第一個參數format爲壓縮的格式 //第二個參數quality爲圖像壓縮比的值,0-100.0 意味着小尺寸壓縮,100意味着高質量壓縮,經常使用的是80 //第三個參數stream爲輸出流 rawBitmap.compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream); } fileOutputStream.flush(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 獲取網絡圖片 * * @param imgUrl 網絡圖片的地 * @param im 網絡圖片 */ public static synchronized void setBitmap(final URL imgUrl, final ImageView im) { final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Bundle data = msg.getData(); Bitmap bitmap = data.getParcelable("bitmap"); // int width, height; // height = bitmap.getHeight(); // width = bitmap.getWidth(); // // Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); // Canvas c = new Canvas(bmpGrayscale); // Paint paint = new Paint(); // ColorMatrix cm = new ColorMatrix(); // cm.setSaturation(0); // ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm); // paint.setColorFilter(f); // c.drawBitmap(bitmap, 0, 0, paint); if (bitmap != null && !bitmap.isRecycled()) { im.setImageBitmap(bitmap); } // bitmap.recycle(); super.handleMessage(msg); } }; // 將文件名MD5加密 final String umd5 = MD5Util.MD5(imgUrl.toString()); final FileUtil fu = FileUtil.getInstance(null); if (fu.existsThumb(umd5)) { Message msg = new Message(); Bundle data = new Bundle(); Bitmap thumb = fu.readThumbFile(umd5); data.putParcelable("bitmap", thumb); msg.setData(data); handler.sendMessage(msg); } else { new Thread(new Runnable() { @Override public void run() { Bitmap bitmap = null; try { bitmap = BitmapFactory.decodeStream(imgUrl.openStream()); fu.writeFileToSD(umd5, bitmap, true); Message msg = new Message(); Bundle data = new Bundle(); data.putParcelable("bitmap", bitmap); msg.setData(data); handler.sendMessage(msg); } catch (Exception e) { } } }).start(); } } /*** * 設置網路圖片爲縮略圖 */ public static void setThumbBitmap(final URL imgUrl, final ImageView im) { setThumbBitmap(imgUrl, im, 100, 100); } /** * 縮略圖 */ public static synchronized void setThumbBitmap(final URL imgUrl, final ImageView im, final int height, final int width) { final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Bundle data = msg.getData(); Bitmap thumb = data.getParcelable("thumb"); if (thumb != null && !thumb.isRecycled()) { im.setImageBitmap(thumb); } super.handleMessage(msg); } }; // 將文件名MD5加密 final String umd5 = MD5Util.MD5(imgUrl.toString()); final FileUtil fu = FileUtil.getInstance(null); if (fu.existsThumb(umd5)) { Message msg = new Message(); Bundle data = new Bundle(); Bitmap thumb = fu.readThumbFile(umd5); data.putParcelable("thumb", thumb); msg.setData(data); handler.sendMessage(msg); } else { new Thread(new Runnable() { @Override public void run() { Bitmap bitmap = null; try { bitmap = BitmapFactory.decodeStream(imgUrl.openStream()); Bitmap thumb = ThumbnailUtils.extractThumbnail(bitmap, width, height); fu.writeFileToSD(umd5, thumb, true); bitmap.recycle(); Message msg = new Message(); Bundle data = new Bundle(); data.putParcelable("thumb", thumb); msg.setData(data); handler.sendMessage(msg); } catch (Exception e) { } } }).start(); } } /** * 獲取圖片的縮略圖 * String filePath 圖片路徑 */ private Bitmap getBitmapThumbnail(String filePath){ BitmapFactory.Options options = new BitmapFactory.Options(); //true那麼將不返回實際的bitmap對象,不給其分配內存空間可是能夠獲得一些解碼邊界信息即圖片大小等信息 options.inJustDecodeBounds = true; //此時rawBitmap爲null Bitmap rawBitmap = BitmapFactory.decodeFile(filePath, options); if (rawBitmap == null) { System.out.println("此時rawBitmap爲null"); } //inSampleSize表示縮略圖大小爲原始圖片大小的幾分之一,若該值爲3 //則取出的縮略圖的寬和高都是原始圖片的1/3,圖片大小就爲原始大小的1/9 //計算sampleSize int sampleSize = computeSampleSize(options, 150, 200*200); //爲了讀到圖片,必須把options.inJustDecodeBounds設回false options.inJustDecodeBounds = false; options.inSampleSize = sampleSize; //原圖大小爲625x690 90.2kB //測試調用computeSampleSize(options, 100, 200*100); //獲得sampleSize=8 //獲得寬和高位79和87 //79*8=632 87*8=696 Bitmap thumbnailBitmap = BitmapFactory.decodeFile(filePath, options); //保存到SD卡方便比較 this.compressAndSaveBitmapToSDCard(thumbnailBitmap, "15.jpg", 80); return thumbnailBitmap; } /** * 獲取圖片縮略圖方法2 * String filePath 圖片路徑 */ public Bitmap getBitmapThumbnail2(String filePath, int newHeight, int newWidth){ //String SDCarePath2=Environment.getExternalStorageDirectory().toString(); //String filePath2=SDCarePath2+"/"+"haha.jpg"; Bitmap tempBitmap = BitmapFactory.decodeFile(filePath); return ThumbnailUtils.extractThumbnail(tempBitmap, newHeight, newWidth); } /** * 從資源文件中獲得圖片 */ public Bitmap getBitmapForRes(Context context,int resId){ return BitmapFactory.decodeResource(context.getResources(), resId); } /** * 獲取資源圖片 */ public static Bitmap getImageFromAssetsFile(Context context, String filename) { Bitmap image = null; AssetManager am = context.getResources().getAssets(); try { InputStream is = am.open(filename); image = BitmapFactory.decodeStream(is); is.close(); } catch (IOException e) { Log.e("ERROR", "FROM BitmapUtil:" + e.getMessage()); } return image; } /** * 獲取SDCard上的圖片 * String filePath 圖片路徑 * return */ private InputStream getBitmapInputStreamFromSDCard(String fileName){ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String SDCarePath = Environment.getExternalStorageDirectory().toString(); String filePath = SDCarePath + File.separator+fileName; File file = new File(filePath); try { FileInputStream fileInputStream = new FileInputStream(file); return fileInputStream; } catch (Exception e) { e.printStackTrace(); } } return null; } /** * 從SDCard中獲取圖片 */ public Bitmap getBitmapForSDCard(String filePath){ return BitmapFactory.decodeFile(filePath, null); } /** * 從SDCard中獲取圖片 */ public Bitmap getBitmapForSDCard2(String fileName){ InputStream inputStream=getBitmapInputStreamFromSDCard(fileName); return BitmapFactory.decodeStream(inputStream); } /** * 設置圖片圓角 */ public Bitmap getRoundBitmap(Context context, Bitmap bitmap, ImageView image){ Bitmap roundBitmap = context.toRoundCorner(bitmap, 40); image.setImageBitmap(roundBitmap); } /** * @param bitmap 須要修改的圖片 * @param pixels 圓角的弧度 * @return 圓角圖片 * 參考資料: http://blog.csdn.net/c8822882/article/details/6906768 */ public Bitmap toRoundCorner(Bitmap bitmap, int pixels) { Bitmap roundCornerBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(roundCornerBitmap); int color = 0xff424242; //int color = 0xff424242; Paint paint = new Paint(); paint.setColor(color); //防止鋸齒 paint.setAntiAlias(true); Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); RectF rectF = new RectF(rect); float roundPx = pixels; //至關於清屏 canvas.drawARGB(0, 0, 0, 0); //先畫了一個帶圓角的矩形 canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); //再把原來的bitmap畫到如今的bitmap!!!注意這個理解 canvas.drawBitmap(bitmap, rect, rect, paint); return roundCornerBitmap; } /** * 設置圖片灰度 */ public static synchronized void setGreyBitmap(final URL imgUrl, final ImageView im) { final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Bundle data = msg.getData(); Bitmap bitmap = data.getParcelable("bitmap"); int width, height; height = bitmap.getHeight(); width = bitmap.getWidth(); Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); Canvas c = new Canvas(bmpGrayscale); Paint paint = new Paint(); ColorMatrix cm = new ColorMatrix(); cm.setSaturation(0); ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm); paint.setColorFilter(f); c.drawBitmap(bitmap, 0, 0, paint); if (bmpGrayscale != null && !bmpGrayscale.isRecycled()) { im.setImageBitmap(bmpGrayscale); } // bitmap.recycle(); super.handleMessage(msg); } }; // 將文件名MD5加密 final String umd5 = MD5Util.MD5(imgUrl.toString()); final FileUtil fu = FileUtil.getInstance(null); if (fu.existsThumb(umd5)) { Message msg = new Message(); Bundle data = new Bundle(); Bitmap thumb = fu.readThumbFile(umd5); data.putParcelable("bitmap", thumb); msg.setData(data); handler.sendMessage(msg); } else { new Thread(new Runnable() { @Override public void run() { Bitmap bitmap = null; try { bitmap = BitmapFactory.decodeStream(imgUrl.openStream()); fu.writeFileToSD(umd5, bitmap, true); Message msg = new Message(); Bundle data = new Bundle(); data.putParcelable("bitmap", bitmap); msg.setData(data); handler.sendMessage(msg); } catch (Exception e) { } } }).start(); } } //參考資料: //http://my.csdn.net/zljk000/code/detail/18212 //第一個參數:本來Bitmap的options //第二個參數:但願生成的縮略圖的寬高中的較小的值 //第三個參數:但願生成的縮量圖的總像素 public static 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 static int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) { //原始圖片的寬 double w = options.outWidth; //原始圖片的高 double h = options.outHeight; System.out.println("========== w="+w+",h="+h); 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 the larger one when there is no overlapping zone. return lowerBound; } if ((maxNumOfPixels == -1) && (minSideLength == -1)) { return 1; } else if (minSideLength == -1) { return lowerBound; } else { return upperBound; } } /** * 獲取SDCard的目錄路徑功能 */ private String getSDCardPath() { String SDCardPath = null; // 判斷SDCard是否存在 boolean IsSDcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); if (IsSDcardExist) { SDCardPath = Environment.getExternalStorageDirectory().toString(); } return SDCardPath; } }
Resources res = context.getResources(); Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.sample_0); //或者用以下方法(BitmapDrawable的構造函數,咱們就會發現與Resource中的openRawResource()接口是相對應的) Resources r = this.getContext().getResources(); Inputstream is = r.openRawResource(R.drawable.my_background_image); BitmapDrawable bmpDraw = new BitmapDrawable(is); Bitmap bmp = bmpDraw.getBitmap();
方法:android
public static Bitmap drawableToBitmap(Drawable drawable) { 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); //canvas.setBitmap(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; }
Drawable drawable = new BitmapDrawable(bmp);
Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);
public byte[] bitmapToBytes(Bitmap bm){} ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); }
private Bitmap Bytes2Bimap(byte[] b){ if(b.length!=0){ return BitmapFactory.decodeByteArray(b, 0, b.length); }else { return null; } }
https://github.com/bumptech/glidegithub
http://blog.csdn.net/buaaroid/article/details/50563982canvas