【问题标题】:Java Android - JPEG Image rotationJava Android - JPEG 图像旋转
【发布时间】:2018-08-24 14:13:40
【问题描述】:

我正在开发一个捕获图像的应用程序,但我想在保存之前旋转 JPEG 图像,我已经看到了这个链接: Android Rotate Picture before saving

这就是我现在正在做的事情。

ByteBuffer byteBuffer = mImage.getPlanes()[0].getBuffer();
byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes);

FileOutputStream fileOutputStream = null;

try {
    fileOutputStream = new FileOutputStream(mImageFileName);
    fileOutputStream.write(bytes);
} catch (IOException e) {
    e.printStackTrace();
}


我试过这样旋转图像:

// Bytes array to bitmap and matrix rotation
Bitmap sourceBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Matrix m = new Matrix();
m.setRotate((float)90, sourceBitmap.getWidth(), sourceBitmap.getHeight());
Bitmap targetBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), m, true);

// Bitmap to bytes array
int size = targetBitmap.getRowBytes() * targetBitmap.getHeight();
ByteBuffer targetByteBuffer = ByteBuffer.allocate(size);
targetBitmap.copyPixelsToBuffer(targetByteBuffer);
bytes = targetByteBuffer.array();

但是当我在我的图库中查看文件时,我无法读取它,图像似乎损坏了。

编辑:在 Android 7.1.1 上不起作用:/ 知道吗?我可以为视频记录做类似的事情吗?

【问题讨论】:

  • 当您保存而不旋转时,是否会将您的图像显示到图库中。?
  • 你分享的链接 - 看看有 17 个赞的答案
  • 是的,@NikunjParadva

标签: java android matrix android-camera2


【解决方案1】:

您正在将您的Bitmap 转换为bytes array, 现在你停止这种方式直接将Bitmap保存到File

Bitmap sourceBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Matrix m = new Matrix();
m.setRotate((float)90, sourceBitmap.getWidth(), sourceBitmap.getHeight());
Bitmap rotatedBitmap= Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), m, true);

// Save Bitmap directly to the file

String filename = "hello.jpg";
File sd = Environment.getExternalStorageDirectory();
File dest = new File(sd, filename);

try {
     FileOutputStream out = new FileOutputStream(dest);
     bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
     out.flush();
     out.close();
    } catch (Exception e) {
     e.printStackTrace();
    }

【讨论】:

  • 如果您得到答案,请点击答案上的复选标记
【解决方案2】:

这个小改动显然成功了!谢谢尼昆吉!

ByteBuffer byteBuffer = mImage.getPlanes()[0].getBuffer();
byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes);

Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Matrix matrix = new Matrix();
matrix.setRotate((float)90, bitmap.getWidth(), bitmap.getHeight());

FileOutputStream fileOutputStream = null;
try {
    fileOutputStream = new FileOutputStream(mImageFileName);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
    fileOutputStream.flush();
    fileOutputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    相关资源
    最近更新 更多