我正在尝试从现有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(没有这样的文件或目录)
如果我刚刚创建文件并且可以访问其URI,那么有人可以向我解释该文件不存在吗?
也许我对此一切都错了?在这种情况下,根据其URI将旋转图像保存到同一位置的正确方法是什么?
答案 0 :(得分:6)
嘿,你可以这样做,用来将位图写入文件。
// 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计划。
答案 1 :(得分:1)
这是一个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)
}
你可以改为定义函数来接受上下文作为参数,使接收器对你来说很方便。