大家好,又见面了,我是全栈君。
这两天改进优化项目中图片上传的代码。考虑到可能有7、8M的比較大的图片,由于要先进行压缩。所以设计到文件的压缩,保存与清空删除操作。
在这里记下笔记。
/** * 压缩并另存为,每次先清空再保存 */ private void compressFile(){ //清空保存文件夹下的旧照片 String saveDir = Environment.getExternalStorageDirectory() + "/bag/uploadPictures"; File imageDir = new File(saveDir); if (imageDir.exists()) { clearFolder(imageDir); }else{ imageDir.mkdirs(); } //推断图片大小。大于300k则压缩 for (int i = 0; i < imagePathList.size(); i++) { Bitmap bitmap = compressImage(imagePathList.get(i)); imagePathList.set(i, saveImage(saveDir,bitmap)); } } /**保存图片,输入保存文件夹和bitmap。以日期命名。返回保存路径 * * @param path * @param bitmap * @return */ private String saveImage(String path ,Bitmap bitmap){ Date dt = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String imageName =sdf.format(dt)+".jpg"; File file = new File(path,imageName ); if (file.exists()) { file.delete(); } try { FileOutputStream out = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); out.flush(); out.close(); Log.d(TAG, "图片已经保存"); return path+"/"+imageName; } catch (FileNotFoundException e) { Log.d(TAG, "文件不存在"); e.printStackTrace(); return ""; } catch (IOException e) { Log.d(TAG, "IO异常"+e.toString()); e.printStackTrace(); return ""; } } /** * 压缩图片 * @param imagePath * @return */ private Bitmap compressImage(String imagePath) { PhotoUpBitmapCache bitmapCache = new PhotoUpBitmapCache(); //取1280*720大小 Bitmap image = bitmapCache.revitionImage(imagePath, 1280,720); //用以下这个行代码会造成OOM,所以必须用Android 自带的方法去先压缩再导入 // Bitmap image = BitmapFactory.decodeFile(imagePath); ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩。把压缩后的数据存放到baos中 int options = 100; while ( baos.toByteArray().length /1024 > 300) { //循环推断假设压缩后图片是否大于100kb,大于继续压缩 baos.reset();//重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中 options -= 5;//每次都降低5% } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片 Log.d(TAG, "文件压缩成功"); return bitmap; } /** * 清空文件夹里面全部子文件 */ private void clearFolder(File file) { if(file.isDirectory()){ File[] childFiles = file.listFiles(); if (childFiles == null || childFiles.length == 0) { return; } for (int i = 0; i < childFiles.length; i++) { childFiles[i].delete(); } return ; } }
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/115669.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...