从SD卡中选择图像,调整图像大小并将其保存回SD卡

我正在一个应用程序,我需要从sd card选择一个图像,并显示在图像视图。 现在我想要用户通过点击一个按钮来减少/增加宽度,然后将其保存回SD卡。

我已经完成了图像采集并在UI上显示。 但无法找到如何调整它。任何人都可以请建议我如何实现它。

就在昨天,我已经做到了

 File dir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); Bitmap b= BitmapFactory.decodeFile(PATH_ORIGINAL_IMAGE); Bitmap out = Bitmap.createScaledBitmap(b, 320, 480, false); File file = new File(dir, "resize.png"); FileOutputStream fOut; try { fOut = new FileOutputStream(file); out.compress(Bitmap.CompressFormat.PNG, 100, fOut); fOut.flush(); fOut.close(); b.recycle(); out.recycle(); } catch (Exception e) {} 

另外不要忘记回收你的bitmaps :它会节省内存。

你也可以得到新建立的文件的路径String: newPath=file.getAbsolutePath();

尝试使用这种方法:

 public static Bitmap scaleBitmap(Bitmap bitmapToScale, float newWidth, float newHeight) { if(bitmapToScale == null) return null; //get the original width and height int width = bitmapToScale.getWidth(); int height = bitmapToScale.getHeight(); // create a matrix for the manipulation Matrix matrix = new Matrix(); // resize the bit map matrix.postScale(newWidth / width, newHeight / height); // recreate the new Bitmap and set it back return Bitmap.createBitmap(bitmapToScale, 0, 0, bitmapToScale.getWidth(), bitmapToScale.getHeight(), matrix, true); } 

您可以使用Bitmap.createScaledBitmap(位图src,int dstWidth,int dstHeight,布尔过滤器)

在Kotlin中没有OutOfMemoryException解决方案

 fun resizeImage(file: File, scaleTo: Int = 1024) { val bmOptions = BitmapFactory.Options() bmOptions.inJustDecodeBounds = true BitmapFactory.decodeFile(file.absolutePath, bmOptions) val photoW = bmOptions.outWidth val photoH = bmOptions.outHeight // Determine how much to scale down the image val scaleFactor = Math.min(photoW / scaleTo, photoH / scaleTo) bmOptions.inJustDecodeBounds = false bmOptions.inSampleSize = scaleFactor val resized = BitmapFactory.decodeFile(file.absolutePath, bmOptions) ?: return file.outputStream().use { resized.compress(Bitmap.CompressFormat.JPEG, 75, it) resized.recycle() } } 

理想情况下,您应该使用多点触控,而不是使用按钮来增加/减少宽度。 这是一个了不起的图书馆。 一旦用户决定保存图像,图像转换矩阵必须永久保存(在你的sqlite数据库中)。 下次用户打开图像时,您需要调用矩阵并将其应用于图像。

我之前已经做了这个。