I am passing JSON string to JavaScript code which contains {"imagePath":"a.svg"} Now instead of passing the path I want to send the image as string(some byte code maybe). I will be parsing this string in JavaScript and writing this as image to document.
            Asked
            
        
        
            Active
            
        
            Viewed 2,016 times
        
    1
            
            
        - 
                    Send it as base64 encoding, so you can put that in the `src` attribute, see http://stackoverflow.com/questions/1207190/embedding-base64-images – Barmar May 22 '15 at 07:00
2 Answers
2
            
            
        Convert svg string to base64 and add base64 string to json as property.
Look at example: https://jsfiddle.net/wLftvees/1/

var decodedJson = {
    img: 
"PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBB"+
"ZG9iZSBJbGx1c3RyYXRvciAxNS4xLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9u"+
...
"NSw4LjU5NS0wLjA5NSwxMC42ODIsMS45MDMiLz4NCjwvc3ZnPg0K"
};
document.getElementById('image').src = 'data:image/svg+xml;base64,' + decodedJson.img;
 
    
    
        Boris Gappov
        
- 2,483
- 18
- 23
0
            
            
        First: Convert your image to String
public static String encodeToString(BufferedImage image, String type) {
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();
        BASE64Encoder encoder = new BASE64Encoder();
        imageString = encoder.encode(imageBytes);
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return imageString;
}
Second: Convert String to image
public static BufferedImage decodeToImage(String imageString) {
    BufferedImage image = null;
    byte[] imageByte;
    try {
        BASE64Decoder decoder = new BASE64Decoder();
        imageByte = decoder.decodeBuffer(imageString);
        ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
        image = ImageIO.read(bis);
        bis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return image;
}
Now you can use 2 function and switch to Javascript to get Image. ^^
 
    
    
        ThanhND25
        
- 86
- 4
