轉載自:代碼很實用所以轉載過來,又因為轉載的也是別人轉載的文章,所以出處不知道,請見諒!
android 將圖片內容解析成字節數組;將字節數組轉換為ImageView可調用的Bitmap對象;圖片縮放;把字節數組保存為一個文件;把Bitmap轉Byte
1 import java.io.BufferedOutputStream; 2 import java.io.ByteArrayOutputStream; 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 8 import android.graphics.Bitmap; 9 import android.graphics.BitmapFactory; 10 import android.graphics.Matrix; 11 12 public class ImageDispose { 13 14 /** 15 * @param 將圖片內容解析成字節數組 16 * @param inStream 17 * @return byte[] 18 * @throws Exception 19 */ 20 public static byte[] readStream(InputStream inStream) throws Exception { 21 byte[] buffer = new byte[1024]; 22 int len = -1; 23 ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 24 while ((len = inStream.read(buffer)) != -1) { 25 outStream.write(buffer, 0, len); 26 } 27 byte[] data = outStream.toByteArray(); 28 outStream.close(); 29 inStream.close(); 30 return data; 31 } 32 33 /** 34 * @param 將字節數組轉換為ImageView可調用的Bitmap對象 35 * @param bytes 36 * @param opts 37 * @return Bitmap 38 */ 39 public static Bitmap getPicFromBytes(byte[] bytes, 40 BitmapFactory.Options opts) { 41 if (bytes != null) 42 if (opts != null) 43 return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, 44 opts); 45 else 46 return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); 47 return null; 48 } 49 50 /** 51 * @param 圖片縮放 52 * @param bitmap 對象 53 * @param w 要縮放的寬度 54 * @param h 要縮放的高度 55 * @return newBmp 新 Bitmap對象 56 */ 57 public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h){ 58 int width = bitmap.getWidth(); 59 int height = bitmap.getHeight(); 60 Matrix matrix = new Matrix(); 61 float scaleWidth = ((float) w / width); 62 float scaleHeight = ((float) h / height); 63 matrix.postScale(scaleWidth, scaleHeight); 64 Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, 65 matrix, true); 66 return newBmp; 67 } 68 69 /** 70 * 把Bitmap轉Byte 71 */ 72 public static byte[] Bitmap2Bytes(Bitmap bm){ 73 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 74 bm.compress(Bitmap.CompressFormat.PNG, 100, baos); 75 return baos.toByteArray(); 76 } 77 78 /** 79 * 把字節數組保存為一個文件 80 */ 81 public static File getFileFromBytes(byte[] b, String outputFile) { 82 BufferedOutputStream stream = null; 83 File file = null; 84 try { 85 file = new File(outputFile); 86 FileOutputStream fstream = new FileOutputStream(file); 87 stream = new BufferedOutputStream(fstream); 88 stream.write(b); 89 } catch (Exception e) { 90 e.printStackTrace(); 91 } finally { 92 if (stream != null) { 93 try { 94 stream.close(); 95 } catch (IOException e1) { 96 e1.printStackTrace(); 97 } 98 } 99 } 100 return file; 101 } 102 }