将base64字符串转换为图像

时间:2014-06-01 12:25:39

标签: java ajax image grails base64

我正在尝试使用jquery插件裁剪/调整用户个人资料图片的大小,即crop.js,它通过ajax将用户图像作为base64发送到我的控制器

$.ajax({
         type: "post",
         dataType: "json",
         url: "${g.createLink(controller: 'personalDetail', action:'uploadUserImage')}",
         data: { avatar: canvas.toDataURL() }

        });

但我无法解码此base64

'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...==' 

string as image,你能指导我如何将base64字符串保存为服务器上的图像吗?

7 个答案:

答案 0 :(得分:53)

在服务器中,执行以下操作:

假设

String data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...=='

然后:

String base64Image = data.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);

然后你可以用以下字节做任何你喜欢的事情:

BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));

答案 1 :(得分:42)

这假定了一些事情,您知道输出文件名是什么以及您的数据是否为字符串。我确定您可以修改以下内容以满足您的需求:

// Needed Imports
import java.io.ByteArrayInputStream;
import sun.misc.BASE64Decoder;


def sourceData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...==';

// tokenize the data
def parts = sourceData.tokenize(",");
def imageString = parts[1];

// create a buffered image
BufferedImage image = null;
byte[] imageByte;

BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();

// write the image to a file
File outputfile = new File("image.png");
ImageIO.write(image, "png", outputfile);

请注意,这只是涉及哪些部分的示例。我根本没有对这段代码进行优化,而且它已经在我的脑海中写下了。

答案 2 :(得分:8)

#include <mutex> #include <stdio.h> class A { private: bool _is; std::mutex _mutex; } // this function runs in Thread A void A::read() { _mutex.lock(); printf("%d", _is); _mutex.unlock(); } // this function runs in Thread B void A::write() { _mutex.lock(); printf("%d", _is); _is = !_is; _mutex.unlock(); } 将默认压缩图像-压缩后的图像尺寸较小,但有时看起来很奇怪。我使用ImageIO.write()保存字节数组数据-这将保留原始图像大小。

代码如下:

BufferedOutputStream

答案 3 :(得分:5)

要解码:

byte[] image = Base64.getDecoder().decode(base64string);

要编码:

String text = Base64.getEncoder().encodeToString(imageData);

答案 4 :(得分:3)

服务器端编码文件/图像到base64String已准备好供客户端使用

public Optional<String> InputStreamToBase64(Optional<InputStream> inputStream) throws IOException{
    if (inputStream.isPresent()) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        FileCopyUtils.copy(inputStream.get(), output);
        //TODO retrieve content type from file, & replace png below with it
        return Optional.ofNullable("data:image/png;base64," + DatatypeConverter.printBase64Binary(output.toByteArray()));
    }

    return Optional.empty();
}

服务器端base64图像/文件解码器

public Optional<InputStream> Base64InputStream(Optional<String> base64String)throws IOException {
    if (base64String.isPresent()) {
        return Optional.ofNullable(new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(base64String.get())));
    }

    return Optional.empty();
}

答案 5 :(得分:2)

  public Optional<String> InputStreamToBase64(Optional<InputStream> inputStream) throws IOException{
    if (inputStream.isPresent()) {
        ByteArrayOutputStream outpString base64Image = data.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);

然后你可以用以下字节做任何你喜欢的事情:

BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));ut = new ByteArrayOutputStream();
        FileCopyUtils.copy(inputStream.get(), output);
        //TODO retrieve content type from file, & replace png below with it
        return Optional.ofNullable("data:image/png;base64," + DatatypeConverter.printBase64Binary(output.toByteArray()));
    }

    return Optional.empty();

答案 6 :(得分:0)

嗨这是我的解决方案

Javascript代码

var base64before = document.querySelector('img').src;
var base64 = base64before.replace(/^data:image\/(png|jpg);base64,/, "");
var httpPost = new XMLHttpRequest();
var path = "your url";
var data = JSON.stringify(base64);

httpPost.open("POST", path, false);
// Set the content type of the request to json since that's what's being sent
httpPost.setRequestHeader('Content-Type', 'application/json');
httpPost.send(data);

这是我的Java代码。

public void saveImage(InputStream imageStream){     InputStream inStream = imageStream;

try {
    String dataString = convertStreamToString(inStream);

    byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(dataString);
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
    // write the image to a file
    File outputfile = new File("/Users/paul/Desktop/testkey/myImage.png");
    ImageIO.write(image, "png", outputfile);

    }catch(Exception e) {
        System.out.println(e.getStackTrace());
    }
}


static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}