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

Ash*_*mar 22 android image bitmap

我正在开发一个应用程序,我需要从中选择一个图像sd card并在图像视图中显示它.现在我希望用户通过单击按钮减小/增加其宽度,然后将其保存回SD卡.

我已经完成了图像拾取并在ui上显示它.但无法找到如何调整它的大小.任何人都可以建议我如何实现它.

MAC*_*MAC 48

就在昨天我做到了这一点

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) {}
Run Code Online (Sandbox Code Playgroud)

另外别忘了回收你的bitmaps:它会节省内存.

您还可以获取新创建的文件String的路径: newPath=file.getAbsolutePath();

  • BitmapFactory.decodeFile()............这会在打开大尺寸图像时抛出OOM异常,你需要使用"选项"才能打开,如果这样做你会得到减少版本的原始图像........ (7认同)

Dim*_*ira 7

没有OutOfMemoryExceptionKotlin的解决方案

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()
    }
}
Run Code Online (Sandbox Code Playgroud)