BitMap、Drawable、inputStream及byte[]互转, 将图片进行base64编码后上传到服务器
//BitMap to inputStream: ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); InputStream isBm = new ByteArrayInputStream(baos .toByteArray()); // BitMap to byte[]: Bitmap defaultIcon = BitmapFactory.decodeStream(in); ByteArrayOutputStream stream = new ByteArrayOutputStream(); defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte[] bitmapdata = stream.toByteArray(); // Drawable to byte[]: Drawable d; // the drawable (Captain Obvious, to the rescue!!!) Bitmap bitmap = ((BitmapDrawable)d).getBitmap(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, bitmap); byte[] bitmapdata = stream.toByteArray(); //byte[] to Bitmap : Bitmap bitmap =BitmapFactory.decodeByteArray(byte[], 0,byte[].length);
将图片base64编码,提交图片到服务器
/** * 通过Base32将Bitmap转换成Base64字符串,上传图片到服务器 */ public static String Bitmap2StrByBase64(Bitmap bit) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); bit.compress(CompressFormat.JPEG, 40, bos);// 参数100表示不压缩 try { bos.flush(); bos.close(); } catch (IOException e) { e.printStackTrace(); } byte[] bytes = bos.toByteArray(); return Base64.encodeToString(bytes, Base64.DEFAULT); }
图片的压缩: http://blog.csdn.net/harryweasley/article/details/51955467