Search code examples
javafilesize

Compare Image Size in KB in Java


I am using an api which gives me the size of an image, such as 200KB (can be MBs also). Now I need to perform some action on images below a specific size. What I am trying to achieve is something like this:

String imgSize = img.getSize();
if(imgSize < 250KB) {
  // Do Something
}

I can't use the relational operator here. What could be the best way to achieve this?


Solution

  • In addition to the previous answer, you can also do something like this. Convert the size to a size in bytes, then use Integer.parseInt(String s) to get an int value that you can check against.

    String bytes = size.replace("KB", "000").replace("MB", "000000");
    
    if (Integer.parseInt(bytes) <= 250000) {
        //Do something.
    }
    

    If you're dealing with fractional numbers, this can work.

    Map<String, Integer> conversions = new HashMap<String, Integer>();
    conversions.put("KB", 1000);
    conversions.put("MB", 1000000);
    
    //Get numbers from String.
    double doubleSize = Double.parseDouble(size.replaceAll("[A-Z]+$", "")); 
    //Get units from String.
    String units = size.replaceAll("[0-9.]", "");  
    
    double bytes = doubleSize * conversions.get(units);
    
    if (bytes <= 250000) {
        //Do something.
    }