需求:服务器指定图片尺寸大小,并且限制图片文件大小,因此在选择图片后需要进行操作,方法如下:
保存图片的时候,会发现实际文件大小大于当前设置的大小,这个问题在最后面解决,先上正确的代码:
1、指定图片尺寸及文件大小及源图片位置及新图片位置:
float hh = 800f;float ww = 480f;int filesize = 100;//单位是K
//源文件位置
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/soon/a.png";
//保存新的文件位置
String savepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/soon/b.png";
2、图片处理方法及调用:
需要先创建文件夹:
String file = Environment.getExternalStorageDirectory().getAbsolutePath(); String filename = "soon"; File appDir = new File(file, filename); if (!appDir.exists()) {appDir.mkdirs(); }
b31.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View v) {compressThreeOne(path); }});
public void compressThreeOne(String srcPath) {BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeFile(srcPath, opts); opts.inJustDecodeBounds = false; int w = opts.outWidth; int h = opts.outHeight; int size = 0; if (w <= ww && h <= hh) {size = 1; } else {double scale = w >= h ? w / ww : h / hh; double log = Math.log(scale) / Math.log(2); double logCeil = Math.ceil(log); size = (int) Math.pow(2, logCeil); }opts.inSampleSize = size; bitmap = BitmapFactory.decodeFile(srcPath, opts); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int quality = 100; press(pressFormat.JPEG, quality, baos); System.out.println(baos.toByteArray().length); while (baos.toByteArray().length > filesize * 1024) {baos.reset(); press(pressFormat.JPEG, quality, baos); quality -= 5; System.out.println(baos.toByteArray().length); }try {baos.writeTo(new FileOutputStream(savepath)); } catch (Exception e) {e.printStackTrace(); } finally {try {baos.flush(); baos.close(); } catch (IOException e) {e.printStackTrace(); }}}
3、文件大小与获取图片大小不一致的问题:
之前在压缩和缩放后,将图片保存至本地,发现了这个问题,:
之前的方法如下:
public void saveImageToGallery(Bitmap bmp) {// 首先保存图片 String file = Environment.getExternalStorageDirectory().getAbsolutePath(); String filename = "soon"; File appDir = new File(file, filename); if (!appDir.exists()) {appDir.mkdirs(); }String fileName = "b.jpg"; File currentFile = new File(appDir, fileName); FileOutputStream fos = null; try {// currentFile.createNewFile(); fos = new FileOutputStream(currentFile); press(pressFormat.JPEG, 100, fos); fos.flush(); } catch (FileNotFoundException e) {e.printStackTrace(); } catch (IOException e) {e.printStackTrace(); } finally {try {if (fos != null) {fos.close(); }} catch (IOException e) {e.printStackTrace(); }}}
结果总会比预算的文件大几倍。
正确的方法是:
baos.writeTo(new FileOutputStream(savepath));