当您调整图像大小时,写入的新图像不包含 EXIF 数据,因此它显示为原始图像,这使得它看起来像是在侧面。
我有一个示例代码向您展示如何保留 EXIF 数据:
public class ImageData {
public byte[] resize(int maxDimension, File imageFile) throws IOException {
DataInputStream inStream = null;
try {
inStream = new DataInputStream(
new BufferedInputStream(
new FileInputStream(imageFile)));
byte[] imageData = IOUtils.toByteArray(inStream);
BufferedImage image = readImage(imageData);
TiffImageMetadata metadata = readExifMetadata(imageData);
image = Scalr.resize(image, maxDimension);
if (metadata != null) {
imageData = writeExifMetadata(metadata, writeJPEG(image));
} else {
imageData = writePNG(image);
}
return imageData;
} catch (IOException | ImageReadException | ImageWriteException e) {
log.error("image resize failed", e);
return null;
} finally {
assert inStream != null;
inStream.close();
}
}
private TiffImageMetadata readExifMetadata(byte[] jpegData) throws ImageReadException, IOException {
ImageMetadata imageMetadata = Imaging.getMetadata(jpegData);
if (imageMetadata == null) {
return null;
}
JpegImageMetadata jpegMetadata = (JpegImageMetadata)imageMetadata;
return jpegMetadata.getExif();
}
private byte[] writeExifMetadata(TiffImageMetadata metadata, byte[] jpegData)
throws ImageReadException, ImageWriteException, IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ExifRewriter().updateExifMetadataLossless(jpegData, out, metadata.getOutputSet());
out.close();
return out.toByteArray();
}
private BufferedImage readImage(byte[] data) throws IOException {
return ImageIO.read(new ByteArrayInputStream(data));
}
private byte[] writeJPEG(BufferedImage image) throws IOException {
ByteArrayOutputStream jpegOut = new ByteArrayOutputStream();
ImageIO.write(image, "JPEG", jpegOut);
jpegOut.close();
return jpegOut.toByteArray();
}
/**
*
* @param image
* @return byte[]
* @throws IOException
* This method calls when the metadata of a JPEG image is null,
* it will convert the JPEG image to PNG
*/
private byte[] writePNG(BufferedImage image) throws IOException {
ByteArrayOutputStream pngOut = new ByteArrayOutputStream();
ImageIO.write(image,"PNG", pngOut);
pngOut.close();
return pngOut.toByteArray();
}
}
你可以像这样使用这个类:
public String convertImageToThumbnail(String path) {
try {
File imageFile = new File(path);
byte[] imageBytes;
String ex = path.substring(path.lastIndexOf(".")+1);
ImageData imageData = new ImageData();
imageBytes = imageData.resize(50, imageFile);
String output = Base64.getEncoder().encodeToString(imageBytes);
return "data:image/"+ex+";base64," + output;
} catch (Exception e) {
log.error("Converting to thumbnail failed", e);
return null;
}
}
您可以使用此示例调整大小并保留 EXIF 数据。
希望它会有用...