Java BufferedImage from String base64ToImage(final String data, final int width, final int height)

Here you can find the source of base64ToImage(final String data, final int width, final int height)

Description

Builds an image from the given base64 encoded text.

License

Apache License

Parameter

Parameter Description
data the base64 encoded image data
width the image's width
height the image's height

Exception

Parameter Description
IOException if the image cannot be built

Return

a BufferedImage built based on the given data

Declaration

public static BufferedImage base64ToImage(final String data, final int width, final int height)
        throws IOException 

Method Source Code


//package com.java2s;
/*//from w ww  .j ava  2s . com
 *  Copyright 2015 Telenav, Inc.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;

public class Main {
    /**
     * Builds an image from the given base64 encoded text.
     *
     * @param data the base64 encoded image data
     * @param width the image's width
     * @param height the image's height
     * @return a {@code BufferedImage} built based on the given data
     * @throws IOException if the image cannot be built
     */
    public static BufferedImage base64ToImage(final String data, final int width, final int height)
            throws IOException {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        final byte[] decodedData = DatatypeConverter.parseBase64Binary(data);
        // Base64.decodeBase64(data);
        try (ByteArrayInputStream bis = new ByteArrayInputStream(decodedData)) {
            image = ImageIO.read(bis);
        }
        return image;
    }
}

Related

  1. base64StringToImage(String imageString)
  2. base64StringToImage(String imageString)
  3. base64StringToImg(final String base64String)
  4. base64ToImage(String base64)
  5. base64ToImg(String base64Strings)
  6. decodeImage(String encoded)
  7. decodeImage(String imageString)