Check Image Size

150 Views Asked by At

I need to check the size of an image and I'm using image magic to do the same. Unfortunately, ImageIO.read is failing for some of our images as the encoding is CMYK and ImageMagick seems to be working fine.

public static void main(String[] args) throws IOException {
    String ImageMagickHome = "C:/Program Files/ImageMagick-7.0.7-Q16";
    String imageToConvert = "G24624-SA286U-17F04.jpg";
    ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c",
            "cd " + ImageMagickHome + " && magick identify " + imageToConvert);
    builder.redirectErrorStream(true);
    InputStream stream = builder.start().getInputStream();
    IOUtils.toString(builder.start().getInputStream());
    String output = IOUtils.toString(builder.start().getInputStream());
    String[] splitted = output.split(" ");
    System.out.println(splitted[2]);

}

I need to check if the size of an image is less then 500*500. But since I'm executing ImageMagic command through process builder, it doesn't give me the result in the way I want.

splitted[2] give me the size but it's string and I can't compare it. Is there a better way to do the same?

The reason, we are not using JMagick is because:

a.) I don't want to add dependency to additional Jar's. ImageMagic comes with our application hence it add no additional dependency. b.) I couldn't find a proper way to install JMagick.

1

There are 1 best solutions below

0
AudioBubble On
//this might solve your problem. can you please confirm if this is the solutionyou are looking for?
    public static void main(String[] args) throws IOException {
        String ImageMagickHome = "C:\\Program Files\\ImageMagick-7.0.8-Q16";
        String imageToConvert = "C:\\1.jpg";
        ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c",
                "cd " + ImageMagickHome + " && magick identify " + imageToConvert);
        builder.redirectErrorStream(true);
        InputStream stream = (builder.start().getInputStream());


        StringBuilder textBuilder = new StringBuilder();
        try (Reader reader = new BufferedReader(new InputStreamReader
                (stream, Charset.forName(StandardCharsets.UTF_8.name())))) {
            int c = 0;
            while ((c = reader.read()) != -1) {
                textBuilder.append((char) c);
            }
            String str= textBuilder.toString();
            String[] splitted = str.split(" ");
            String[]str2=splitted[2].split("x");
            System.out.println(splitted[2]);
          double imageSize= 500*500;
          double testImage=Double.parseDouble(str2[0])*Double.parseDouble(str2[0]);
          String ratio = String.valueOf(((testImage / imageSize)*100));
          System.out.println("Image size is in ratio: "+ratio);
        }
    }