Skip to content

Instantly share code, notes, and snippets.

@appleshan
Created November 30, 2022 07:21
Show Gist options
  • Save appleshan/0a58af712cc2670dc515a819973bc835 to your computer and use it in GitHub Desktop.
Save appleshan/0a58af712cc2670dc515a819973bc835 to your computer and use it in GitHub Desktop.
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @Description: Java 删除敏感 Exif
* https://ld246.com/article/1592708224683
* @Author apple.shan@gmail.com
* @Date 2022/11/29
**/
public class ExifRewriter {
private static final Logger LOGGER = LoggerFactory.getLogger(ExifRewriter.class);
public static byte[] removeExif(final byte[] bytes) {
/*
https://www.media.mit.edu/pia/Research/deepview/exif.html#ExifMarker
*/
try {
final byte b0 = bytes[0];
final byte b1 = bytes[1];
// FF D8
if (-1 != b0 || -40 != b1) {
// not jpeg
return bytes;
}
// exif seg: FF E1
if (-1 != bytes[2] || -31 != bytes[3]) {
// no exif
return bytes;
}
String len0 = Integer.toHexString(bytes[4]);
if (2 > len0.length()) {
len0 = "0" + len0;
} else {
len0 = len0.substring(len0.length() - 2);
}
String len1 = Integer.toHexString(bytes[5]);
if (2 > len1.length()) {
len1 = "0" + len1;
} else {
len1 = len1.substring(len1.length() - 2);
}
final String lenStr = len0 + "" + len1;
final int len = Integer.parseInt(lenStr, 16);
final byte[] ret = new byte[bytes.length - len - 4 - 2];
ret[0] = -1;
ret[1] = -40;
System.arraycopy(bytes, 4 + len, ret, 2, ret.length - 2);
return ret;
} catch (final Exception e) {
LOGGER.error("Removes Exif failed: ", e);
return bytes;
}
}
public static void main(String[] args) throws IOException {
String testImageFilePath = "C:/Users/danxiao/Pictures/Camera Roll/GPS/test_image_file.jpg";
File imageFile = new File(testImageFilePath);
String testImageFile2Path = "C:/Users/danxiao/Pictures/Camera Roll/GPS/test_image_file2.jpg";
File imageFile2 = new File(testImageFile2Path);
//获取文件输入流
FileInputStream contentStream = new FileInputStream(imageFile);
byte[] content1 = IOUtils.toByteArray(contentStream);
byte[] content2 = removeExif(content1);
FileUtils.writeByteArrayToFile(imageFile2, content2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment