从 URI 旋转图像并将旋转后的图像保存到同一位置

Rotate Image from URI and save the rotated image to the same place

我正在尝试从现有 URI 创建位图,旋转位图并将其保存到与 JPEG 文件相同的位置。这是我尝试了几种解决方案后的当前代码:

try {
    // Get the Bitmap from the known URI. This seems to work.
    Bitmap bmp = MediaStore.Images.Media.getBitmap(this.getContentResolver(), this.currUserImgUri);

    // Rotate the Bitmap thanks to a rotated matrix. This seems to work.
    Matrix matrix = new Matrix();
    matrix.postRotate(-90);
    bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);

    // Create an output stream which will write the Bitmap bytes to the file located at the URI path.
    File imageFile = new File(this.currUserImgUri.getPath());
    FileOutputStream fOut = new FileOutputStream(imageFile); // --> here an Exception is catched; see below.
    // The following doesn't work neither:
    // FileOutputStream fOut = new FileOutputStream(this.currUserImgUri.getPath());

    // Write the compressed file into the output stream
    bmp.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
    fOut.flush();
    fOut.close();

} catch (FileNotFoundException e1) {
    e1.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

捕获到的异常如下:

java.io.FileNotFoundException: /external/images/media/8439: open failed: ENOENT (No such file or directory)

任何人都可以向我解释一下,如果我刚刚创建文件并可以访问其 URI,文件怎么会不存在?

也许我完全错了?在这种情况下,根据其 URI 将旋转后的图像保存到相同位置的正确方法是什么?

嘿,你可以使用 .

将位图写入文件
// Rotate the Bitmap thanks to a rotated matrix. This seems to work.
   Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), photoURI);
   Matrix matrix = new Matrix();
   matrix.postRotate(90);
   Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
   //learn content provider for more info
   OutputStream os=getContext().getContentResolver().openOutputStream(photoURI);
   bmp.compress(Bitmap.CompressFormat.PNG,100,os);

不要忘记刷新并关闭输出流。 实际上内容提供者有它自己的 uri 方案。

这是一个 Kotlin 扩展函数,给定图像的 URI,将旋转图像并将其再次存储在相同的 URI 中。

fun Context.rotateImage(imageUri: uri, angle: Float) {

    // (1) Load from where the URI points into a bitmap    
    val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri)

    // (2) Rotate the bitmap
    val rotatedBitmap = bitmap.rotatedBy(angle)

    // (3) Write the bitmap to where the URI points
    try {
        contentResolver.openOutputStream(imageUri).also {
            rotateBitmap.compress(Bitmap.CompressFormat.PNG, 100, it)
        }
    } catch (e: IOException) {
        // handle exception
    }
}

fun Bitmap.rotatedBy(angle: Float) {
    val matrix = Matrix().apply { postRotate(angle) }
    return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}

您可以改为定义接受上下文作为参数的函数,让接收者随心所欲。