/** * 压缩图片直到容量小于指定值(kb),并保存到sdcard * * @param relativePath * @param fileName * @param bm * @param capacity * @return */ public static int saveBitmap2SDWithCapacity( String relativePath, String fileName, Bitmap bm, int capacity) { if (!relativePath.endsWith("/")) { relativePath = relativePath + "/"; } File file = null; FileOutputStream out = null; ByteArrayInputStream bais = null; try { creatSDDir(relativePath); file = creatSDFile(relativePath + fileName); out = new FileOutputStream(file.getPath()); // bm.compress(Bitmap.CompressFormat.JPEG, 90, out); bais = compressImage(bm, capacity); byte[] buffer = new byte[1024]; int len = 0; while ((len = bais.read(buffer)) != -1) { out.write(buffer, 0, len); } out.flush(); return 0; } catch (Exception e) { e.printStackTrace(); return -1; } finally { ABIOUtil.closeIO(out, bais); } }
/** * 先质量压缩到指定百分比(0% ~ 90%),再把bitmap保存到sd卡上 * * @param filePath * @param bm * @param quality * @return */ public static int saveBitmap2SDAbsolute(String filePath, Bitmap bm, int quality) { File file = null; FileOutputStream out = null; try { file = new File(filePath); if (!file.exists()) { file.createNewFile(); } out = new FileOutputStream(file.getPath()); bm.compress(Bitmap.CompressFormat.JPEG, quality, out); return 0; } catch (Exception e) { e.printStackTrace(); return -1; } finally { ABIOUtil.closeIO(out); } }
/** * 先质量压缩到指定百分比(0% ~ 90%),再把bitmap保存到sd卡上 * * @param relativePath * @param fileName * @param bm * @param quality * @return */ public static int saveBitmap2SD(String relativePath, String fileName, Bitmap bm, int quality) { if (!relativePath.endsWith("/")) { relativePath = relativePath + "/"; } File file = null; FileOutputStream out = null; try { creatSDDir(relativePath); file = creatSDFile(relativePath + fileName); out = new FileOutputStream(file.getPath()); bm.compress(Bitmap.CompressFormat.JPEG, quality, out); return 0; } catch (Exception e) { e.printStackTrace(); return -1; } finally { ABIOUtil.closeIO(out); } }
/** 将一个InputStream里面的数据写入到SD卡中 */ public static File write2SDFromInput(String relativePath, String fileName, InputStream input) { if (!relativePath.endsWith("/")) { relativePath = relativePath + "/"; } File file = null; OutputStream output = null; try { creatSDDir(relativePath); file = creatSDFile(relativePath + fileName); output = new FileOutputStream(file); byte buffer[] = new byte[4 * 1024]; int length = 0; while ((length = input.read(buffer)) != -1) { output.write(buffer, 0, length); } output.flush(); } catch (Exception e) { e.printStackTrace(); } finally { ABIOUtil.closeIO(output); } return file; }