将base64字符串转换为图像

Convert base64 string to image(将base64字符串转换为图像)

本文介绍了将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...==' 

string as Image,你们能指导我如何将我的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字符串转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将base64字符串转换为图像

基础教程推荐