How to convert images in apple’s new HEIC format to jpg in java?
Asked Answered
F

3

8

I have few thousand images in HEIC format that need to be converted to jpg/png. Conversion needs to happen in a backend process preferably java.

What is the best way available to do this in java? If not, can anyone point me to a tutorial that explains how jpg can be obtained from HEIC format?

Food answered 11/5, 2018 at 23:42 Comment(0)
L
0

ImageMagick is great for converting images from the command line. There are two different Java interfaces, JMagick and im4java.

See the Image magick java question for tips how to get started.

Lesslie answered 8/12, 2022 at 20:38 Comment(0)
A
0

You can use im4java and ImageMagick to convert heic to jpeg. The following code may help you.

public static byte[] convertHEICtoJPEG(byte[] heicBytes) throws IOException, InterruptedException, IM4JavaException {
    IMOperation op = new IMOperation();
    op.addImage("-");
    op.addImage("jpeg:-");
    File tempFile = File.createTempFile("temp", ".heic");
    try (FileOutputStream fos = new FileOutputStream(tempFile)) {
        fos.write(heicBytes);
    }
    FileInputStream fis = new FileInputStream(tempFile);
    Pipe pipeIn  = new Pipe(fis,null);
    ConvertCmd convert = new ConvertCmd();
    convert.setSearchPath(IMAGE_MAGICK_PATH);
    convert.setInputProvider(pipeIn); 
    Stream2BufferedImage s2b = new Stream2BufferedImage();
    convert.setOutputConsumer(s2b);
    convert.run(op);
    BufferedImage image = s2b.getImage();
    byte[] imageBytes = imageToBytes(image);
    fis.close();
    return imageBytes;

}


private static byte[] imageToBytes(BufferedImage image) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "jpeg", baos);
    baos.flush();
    byte[] imageBytes = baos.toByteArray();
    baos.close();
    return imageBytes;
}
Addieaddiego answered 26/2 at 11:40 Comment(2)
private static final String IMAGE_MAGICK_PATH = "C:\\Program Files\\ImageMagick-7.1.1-Q16-HDRI";Addieaddiego
You are aware that you can edit your answer? ;)Imagination
B
-2

I've bumped into libheif library recently that is designed to fulfill your task - https://github.com/strukturag/libheif

There is also blog post that explains how to create wrapper bash script and use it to perform conversion using command line : https://stuffjasondoes.com/2019/07/10/batch-convert-heic-to-jpg-in-linux/

I presume you can call above script with ZT Process Executor ( https://github.com/zeroturnaround/zt-exec) or just use old plain Runtime.exec().

Or even get fancier and use JNI to compile with above library for better performance.

Bonanno answered 15/9, 2020 at 3:10 Comment(1)
running CLI scripts programmatically is super hacky and should be the absolute last resortTalanta

© 2022 - 2024 — McMap. All rights reserved.