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?

3 answers

  • answered 2018-04-17 06:06 JoschJava

    Check with:

    imgSize.endsWith("KB");
    

    Extract the number with a regex and multiply accordingly.

  • answered 2018-04-17 06:06 Roshana Pitigala

    Determine whether the imgSize is in KB or MB. Convert it to KB if in MB and use it.

    String imgSize = "";
    int imgSizeKB = 0;
    
    switch (imgSize.toUpperCase()) {
        case "KB":
            imgSizeKB = (Integer.parseInt(imgSize.split("KB")[0]));
            break;
        case "MB":
            imgSizeKB = (Integer.parseInt(imgSize.split("MB")[0]) * 1024);
            break;
    }
    
    if(imgSizeKB < 250){
        // Do Something
    }
    

    Now you can use if statements as imgSizeKB is an int.

  • answered 2018-04-17 06:06 Riaan Nel

    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.
    }