Convert base64 string to image(将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字符串转换为图像
基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01