Encode image from URL in Base64 in Java
Asked Answered
M

5

13

I want to encode and save from an URL images in Base64. I found several example doing the encoding from a local file but not from an URL. Is there a possibility to do that?

I tried something like that, but unsuccessfully. Any clue,help? Thanks for your answer.

    public static void main(String[] args)  {
    String imageUrl = "http://www.avajava.com/images/avajavalogo.jpg";
    String destinationFile = "image.jpg";

    try {           
        // Reading a Image file from file system
        URL url = new URL(imageUrl);
        InputStream is = url.openStream();

        FileInputStream imageInFile = new FileInputStream(is.toString());
        byte imageData[] = new byte[2048];
        imageInFile.read(imageData);

        // Converting Image byte array into Base64 String
        String imageDataString = encodeImage(imageData);
        System.out.println("imageDataString : " + imageDataString);




        System.out.println("Image Successfully Manipulated!");
    } catch (FileNotFoundException e) {
        System.out.println("Image not found" + e);
    } catch (IOException ioe) {
        System.out.println("Exception while reading the Image " + ioe);
    }

}

/**
 * Encodes the byte array into base64 string
 *
 * @param imageByteArray - byte array
 * @return String a {@link java.lang.String}
 */
public static String encodeImage(byte[] imageByteArray) {
    return Base64.encodeBase64URLSafeString(imageByteArray);
}
Monstrous answered 25/6, 2014 at 20:13 Comment(2)
FileInputStream imageInFile = new FileInputStream(is.toString()); this is wrong, read the API docs, make sure you understand exactly what each line in your code is doing.Larrabee
I know this a the wrong part. I took an example wich take a File. But I tried to adapt it with a URL and InputStreamMonstrous
I
4

You should not use FileInputStream.

Use something like:

URL url = new URL(imageUrl);
BufferedInputStream bis = new BufferedInputStream(url.openConnection().getInputStream());

Also you need to read data in loop until you read all bytes of image.

Infrasonic answered 25/6, 2014 at 20:35 Comment(0)
S
14

Try this function by passing image url in parameter.

private String getByteArrayFromImageURL(String url) {

    try {
        URL imageUrl = new URL(url);
        URLConnection ucon = imageUrl.openConnection();
        InputStream is = ucon.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int read = 0;
        while ((read = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, read);
        }
        baos.flush();
        return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
    } catch (Exception e) {
        Log.d("Error", e.toString());
    }
    return null;
}
Scat answered 8/8, 2017 at 5:48 Comment(1)
For multiple downloads, add ucon.setRequestProperty("connection","close");Danieldaniela
S
7

Following code converts image into the base64 string:

public String getBase64EncodedImage(String imageURL) throws IOException {
    java.net.URL url = new java.net.URL(imageURL); 
    InputStream is = url.openStream();  
    byte[] bytes = org.apache.commons.io.IOUtils.toByteArray(is); 
    return Base64.encodeBase64String(bytes);
}

P.S. Above code uses commons-io as a dependency.

Sat answered 17/8, 2017 at 15:56 Comment(0)
R
6
/**
     *
     * @param url - web url
     * @return - Base64 String
     * Method used to Convert URL to Base64 String
     */
    public String convertUrlToBase64(String url) {
        URL newurl;
        Bitmap bitmap;
        String base64 = "";
        try {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            newurl = new URL(url);
            bitmap = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            base64 = Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return base64;
    }
Russia answered 24/5, 2019 at 9:5 Comment(0)
I
4

You should not use FileInputStream.

Use something like:

URL url = new URL(imageUrl);
BufferedInputStream bis = new BufferedInputStream(url.openConnection().getInputStream());

Also you need to read data in loop until you read all bytes of image.

Infrasonic answered 25/6, 2014 at 20:35 Comment(0)
L
0

Do you understand what this line does?

FileInputStream imageInFile = new FileInputStream(is.toString());

First it calls toString on an InputStream object. That will result in a string that looks something like: InputStream@23e5aa. Then it tries to open a file with that name. You don't want to read a file named InputStream@23e5aa, so this is totally wrong.

What you want to do instead is read all the bytes in the original InputStream is into a byte array. How to do that is explained in the answers to this question:

Convert InputStream to byte array in Java

Larrabee answered 25/6, 2014 at 20:38 Comment(1)
thanks for the explanation. Finally, I used something like that.url = new URL(imageUrl); InputStream is = url.openStream(); byte[] bytes = IOUtils.toByteArray(is); imageDataString = encodeImage(bytes);Monstrous

© 2022 - 2024 — McMap. All rights reserved.