Created
April 13, 2020 02:54
-
-
Save kinow/2bee04862eebc43026a72383212c0248 to your computer and use it in GitHub Desktop.
Removing metadata from JPEG with Commons Imaging
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.apache.commons.imaging.formats.jpeg.xmp; | |
import java.io.DataOutputStream; | |
import java.io.File; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.OutputStream; | |
import java.util.ArrayList; | |
import java.util.List; | |
import org.apache.commons.imaging.ImageReadException; | |
import org.apache.commons.imaging.common.bytesource.ByteSource; | |
import org.apache.commons.imaging.common.bytesource.ByteSourceFile; | |
import org.apache.commons.imaging.formats.jpeg.JpegConstants; | |
import org.apache.commons.imaging.formats.jpeg.JpegUtils; | |
import org.apache.commons.imaging.formats.jpeg.xmp.JpegRewriter.JFIFPiece; | |
import org.apache.commons.imaging.formats.jpeg.xmp.JpegRewriter.JFIFPieceImageData; | |
import org.apache.commons.imaging.formats.jpeg.xmp.JpegRewriter.JFIFPieceSegment; | |
public class RemoveMetadata { | |
public static void main(String[] args) throws Exception { | |
File file = new File("/tmp/01.jpg"); | |
ByteSource byteSource = new ByteSourceFile(file); | |
final List<JFIFPiece> pieces = new ArrayList<>(); | |
JpegUtils.Visitor visitor = new JpegUtils.Visitor() { | |
@Override | |
public boolean visitSegment(int marker, byte[] markerBytes, int segmentLength, byte[] segmentLengthBytes, | |
byte[] segmentData) throws ImageReadException, IOException { | |
// keep only the APP0 marker | |
if ("ffe0".equals(Integer.toHexString(marker))) { | |
final JFIFPiece piece = new JFIFPieceSegment(marker, markerBytes, segmentLengthBytes, segmentData); | |
pieces.add(piece); | |
} | |
return true; | |
} | |
@Override | |
public void visitSOS(int marker, byte[] markerBytes, byte[] imageData) { | |
pieces.add(new JFIFPieceImageData(markerBytes, imageData)); | |
} | |
@Override | |
public boolean beginSOS() { | |
return true; | |
} | |
}; | |
new JpegUtils().traverseJFIF(byteSource, visitor); | |
OutputStream newImage = new FileOutputStream(new File("/tmp/02.jpg")); | |
try (DataOutputStream os = new DataOutputStream(newImage)) { | |
JpegConstants.SOI.writeTo(os); | |
for (final JFIFPiece piece : pieces) { | |
piece.write(os); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment