How to encode an image into base64 within processing?

edited June 2015 in How To...

It's a simple question to which I'ven't got a satisfactory answer being entry level programmer in processing. It's simple to do in Python though.. How to encode an image into base64 within processing and get the encoded string?

Any easy way to do it? Would much appreciate it.. Thanks.

Answers

  • edited May 2015 Answer ✓

    Colors in Processing are an integer behind the scenes which is 32 bits. Not sure why you would need them to be stored with 64 bits

    Edit: What I meant was could you explain why you need 64 bit? You could always store two colors per 64 bit I guess

  • I need for a purpose > for uploading an image to tumblr from Processing

  • I need for a purpose > for uploading an image to tumblr from Processing

  • Answer ✓

    Not sure about Processing, but since (IIRC) you can run Java code in a sketch I'd suggest looking up a Java solution and trying that...

  • Yes I'm doing that but some other libraries have some duplication problems iwth the apache it's using for encoding..

  • edited May 2015

    Is there a simple way I can implement some java code like this in Processing to encode in base64.

    package com.myjeeva.image;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import org.apache.commons.codec.binary.Base64;
    
    /**
     * @desc Image manipulation - Conversion
     * 
     * @filename ImageManipulation.java
     * @author Jeevanandam M. (jeeva@myjeeva.com)
     * @copyright myjeeva.com
     */
    public class ImageManipulation {
    
        public static void main(String[] args) {
    
            File file = new File("/Users/jeeva/Pictures/wallpapers/water-drop.jpg");
    
            try {            
                // Reading a Image file from file system
                FileInputStream imageInFile = new FileInputStream(file);
                byte imageData[] = new byte[(int) file.length()];
                imageInFile.read(imageData);
    
                // Converting Image byte array into Base64 String
                String imageDataString = encodeImage(imageData);
    
                // Converting a Base64 String into Image byte array
                byte[] imageByteArray = decodeImage(imageDataString);
    
                // Write a image byte array into file system
                FileOutputStream imageOutFile = new FileOutputStream(
                        "/Users/jeeva/Pictures/wallpapers/water-drop-after-convert.jpg");
    
                imageOutFile.write(imageByteArray);
    
                imageInFile.close();
                imageOutFile.close();
    
                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);
        }
    
        /**
         * Decodes the base64 string into byte array
         *
         * @param imageDataString - a {@link java.lang.String}
         * @return byte array
         */
        public static byte[] decodeImage(String imageDataString) {
            return Base64.decodeBase64(imageDataString);
        }
    }
    
  • Answer ✓

    the two calls to Base64.encodeBase64 and decodeBase64 are doing the heavy lifting there. they are both part of the imported org.apache.commons.codec.binary.Base64 library. (there are a million other versions too.)

    you should be able to just import that same library into your processing code, at the top, and call the methods just the same.

  • Answer ✓

    (asimes seems confused over what base64 encoding is. it's a way of representing binary data as strings of printable characters, typically a-z, A-Z, 0-9 and two others. it dates back to when some networks would only handle 7 bits, but is used now for things like storing favicons and small images and other binary data in text files.)

    http://en.wikipedia.org/wiki/Base64

  • Answer ✓

    @koogs, thanks

  • edited May 2015

    Any good resource with easily digestible example @koogs

  • edited May 2015

    @koogs Since there are lot of issues like image to byte array and then conversion. I'm struggling for sometime now. Any link you may suggest, I might have tried already..

    So it would help if I can get some help in coding here:

    1)Converting image to byte[] data ( --trying loadPixel() method) 2)feeding that byte array to a base 64 string(which I suppose I can do it from above )

    This what I'm trying to do but not working::

    `

     import org.apache.commons.codec.binary.Base64;   
    
     PImage img;
    
     void setup(){
    
     size(632, 433);
     img = loadImage("test.png");
     size(img.width, img.height);
     img.loadPixels();
     for (int y = 0; y < img.height; y++ ) {
     for (int x = 0; x < img.width; x++ ) {
     int loc = x + y*width;
     //I guess this is the only thing that would be converted into bytes 
     // or is it anything else?
     int data = img.pixels[loc];
     byte convertedData = byte(data);
     //Now how do I make a byte array here?
     //byte[] imageByte = .. ??
     }
     }
     String imageDataString = Base64.encodeBase64URLSafeString(imageByte);
     println(imageDataString);
     }
    
     void draw(){
    
     }
    

    `

    Also if I try the previous java code directly in Processing(after replacing the top package com.myjeeva.image; and all the public static void with public void), I get the folllowing errors:

    Usage: PApplet <appletname> For additional options, see the Javadoc for PApplet Could not run the sketch (Target VM failed to initialize). Make sure that you haven't set the maximum available memory too high. For more information, read revisions.txt and Help → Troubleshooting.

    to which I've checked and I my processing's memory is just 10 mb(which is default preference) ..

  • Answer ✓

    Java 8 (at least!) has native Base64 support: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html
    I thought it was made earlier, but apparently no.

  • Answer ✓

    Ah, I found back an old sketch. I wasn't so wrong, Base64 is built in Java in earlier versions, but it was well hidden... :-)

    import javax.xml.bind.DatatypeConverter;
    
    void setup()
    {
      String b64 = DatatypeConverter.printBase64Binary("Java has well hidden resources!".getBytes());
      println(b64);
      byte[] origB = DatatypeConverter.parseBase64Binary(b64);
      String orig = new String(origB);
      println(orig);
      exit();
    }
    
  • edited June 2015

    I found a easy hack around.

    I invoked an external terminal command from Processing and the one line command was using openssl to encode the picture file into base64 and save it in a txt file..

    `

    String term = "openssl base64 -in   /Users/saurabh.datta/Documents/Processing/sketches/tinderBot_101/application.macosx64/infoImage.jpg -out /Users/saurabh.datta/Documents/Processing/sketches/tinderBot_101/application.macosx64/encodedB64.txt";  //change your own paths
    
    try {
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec(term);
    } catch (Exception e){}
    

    `

    next I was loading the text file, opening the contents in a string array.. Cleaning it up in a single string and use it in the Tumblr's Temboo API as the data of the file to be uploaded..

  • @PhiLho I found it before and it worked but I'm not sure how to use the image here.

Sign In or Register to comment.