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

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

问题描述

我正在尝试使用 jquery 插件即crop.js 裁剪/调整用户配置文件图像的大小,该插件通过ajax 将用户图像作为base64 发送到我的控制器

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() }

        });

但我无法解码这个 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);

请注意,这只是所涉及部分的示例.我根本没有优化这段代码,它是我脑子里写的.

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天全站免登陆