Search code examples
javaandroidimage-processingpicassoandroid-camera-intent

Android: Click new image, compress it and upload it to server


Which is the best way to go about the task? Either of these question answered would do it-

1) How to compress an image without losing clarity?

or

2) How to start camera on low resolution in our app?

I know how to click images by CameraIntent, or select images through gallery in an application, and also upload it to server. But since the images can be too large if clicked by a camera of high pixel density (my 13MP phone's camera click 3MB images) but we cannot upload that. I need the size to be less than 300KB, preferably around 150KB to 200KB without losing the clarity of the pic. Do we have libraries for this in Android? The pictures would be of hand-written text. As of this being impossible, I have tried turning down the resolution of a camera manually to 2MP or VGA, even then the pictures would be clear enough.

Alternatively, if we start Camera on low resolution, that would also do it.


Solution

  • Use the following function to scale any image to any dimension

    public static BufferedImage getScaledImage(Image srcImg, int w, int h) {
            BufferedImage resizedImg = new BufferedImage(w, h, Transparency.TRANSLUCENT);
            Graphics2D g2 = resizedImg.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2.drawImage(srcImg, 0, 0, w, h, null);
            g2.dispose();
            return resizedImg;
        }
    

    To call the function, use the following code:

    File file = new File(path);
    image = ImageIO.read(file);
    newImage = getScaledImage(image, int width, int height);
    File outputfile = new File("background.png");
    ImageIO.write(newImage, "png", outputfile);