Android 图像调整大小并保留 EXIF 数据(方向、旋转等)

作者:编程家 分类: android 时间:2025-06-23

Android 图像调整大小并保留 EXIF 数据(方向、旋转等)

在Android开发中,我们经常需要对图像进行调整大小,以适应不同的需求和场景。然而,调整图像大小常常会导致丢失图像的EXIF数据,包括方向、旋转等信息。本文将介绍如何在Android中调整图像大小的同时保留其EXIF数据。

什么是EXIF数据

EXIF(Exchangeable Image File Format)是一种用于存储图像和音频文件的元数据格式。它包含了拍摄设备的制造商、模型、拍摄日期、方向、旋转角度等信息。在Android中,我们可以通过读取图像的EXIF数据来获取这些信息并进行相应的处理。

调整图像大小并保留EXIF数据的步骤

要实现在调整图像大小的同时保留其EXIF数据,我们可以按照以下步骤进行操作:

1. 读取原始图像的EXIF数据:首先,我们需要读取原始图像的EXIF数据。可以使用Android提供的ExifInterface类来实现。例如,可以通过以下代码读取EXIF数据:

java

ExifInterface exif = new ExifInterface(filePath);

int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);

2. 调整图像大小:接下来,我们可以使用Bitmap类来调整图像的大小。可以根据需要指定新的宽度和高度,并使用Bitmap.createScaledBitmap()方法来实现。例如,可以使用以下代码将图像调整为指定的宽度和高度:

java

Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, false);

3. 保存调整后的图像:调整图像大小后,我们需要将其保存到指定的路径,并保留原始图像的EXIF数据。可以使用Bitmap.compress()方法将Bitmap对象保存为图像文件。在保存之前,我们需要将EXIF数据写回到调整后的图像中。例如,可以使用以下代码保存调整后的图像,并保留EXIF数据:

java

resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);

outputStream.flush();

outputStream.close();

ExifInterface newExif = new ExifInterface(newFilePath);

newExif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(orientation));

newExif.saveAttributes();

示例代码

下面是一个完整的示例代码,演示了如何在Android中调整图像大小并保留其EXIF数据:

java

public void resizeImageWithExifData(String filePath, int newWidth, int newHeight, String newFilePath) {

try {

// 读取原始图像的EXIF数据

ExifInterface exif = new ExifInterface(filePath);

int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);

// 调整图像大小

Bitmap originalBitmap = BitmapFactory.decodeFile(filePath);

Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, false);

// 保存调整后的图像并保留EXIF数据

FileOutputStream outputStream = new FileOutputStream(newFilePath);

resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);

outputStream.flush();

outputStream.close();

ExifInterface newExif = new ExifInterface(newFilePath);

newExif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(orientation));

newExif.saveAttributes();

// 清理资源

originalBitmap.recycle();

resizedBitmap.recycle();

} catch (IOException e) {

e.printStackTrace();

}

}

通过以上步骤,我们可以在Android中调整图像大小的同时保留其EXIF数据。首先,我们需要读取原始图像的EXIF数据;然后,调整图像大小;最后,保存调整后的图像并将EXIF数据写回。这样,我们就可以在调整图像大小的同时保留其EXIF数据,确保图像在不同场景下的正确显示和处理。