base64转换字符串图像 [英] Convert base64 string to image

查看:272
本文介绍了base64转换字符串图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想作物/使用jQuery插件即crop.js它发送用户图像为base64通过AJAX到我的控制器

I am trying to crop/resize user profile image using jquery plugin namely crop.js which sends user image as base64 via ajax to my controller as

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

        });

但我无法去$ C C本的base64 $

but I unable to decode this base64

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

字符串作为图片,你们可以指导我怎么能我的base64字符串保存为图像在我的服务器?

string as Image,Can you guys guide me how can I save my base64 string as image on my server?.

推荐答案

这假定几件事情,你知道什么是输出文件的名称将会和您的数据来作为一个字符串。我敢肯定,你可以修改以下,以满足您的需求:

This assumes a few things, that you know what the output file name will be and that your data comes as a string. I'm sure you can modify the following to meet your needs:

// 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);

请注意,这是部分涉及哪些只是一个例子。我还没有在所有优化这个code和它注销了我的头顶。

Please note, this is just an example of what parts are involved. I haven't optimized this code at all and it's written off the top of my head.

这篇关于base64转换字符串图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆