Java 将 base64 字符串转换为图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23979842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert base64 string to image
提问by Abs
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
我正在尝试使用 jquery 插件裁剪/调整用户配置文件图像的大小,即crop.js,它通过 ajax 将用户图像作为 base64 发送到我的控制器
$.ajax({
type: "post",
dataType: "json",
url: "${g.createLink(controller: 'personalDetail', action:'uploadUserImage')}",
data: { avatar: canvas.toDataURL() }
});
but I unable to decode this base64
但我无法解码这个 base64
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...=='
string as Image,Can you guys guide me how can I save my base64 string as image on my server?.
字符串作为图像,你们能指导我如何将我的 base64 字符串保存为我的服务器上的图像吗?
采纳答案by Joshua Moore
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.
请注意,这只是涉及哪些部分的示例。我根本没有优化这段代码,它已经在我的脑海中写下了。
回答by geo
In the server, do something like this:
在服务器中,执行如下操作:
Suppose
认为
String data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...=='
Then:
然后:
String base64Image = data.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
Then you can do whatever you like with the bytes like:
然后你可以对字节做任何你喜欢的事情:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));
回答by iamiddy
Server side encoding files/Images to base64String ready for client side consumption
服务器端将文件/图像编码为 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();
}
Server side base64 Image/File decoder
服务器端 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();
}
回答by mero
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);
Then you can do whatever you like with the bytes like:
然后你可以对字节做任何你喜欢的事情:
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();
回答by paulrda
Hi This is my solution
嗨,这是我的解决方案
Javascriptcode
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);
This is my Javacode.
这是我的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() : "";
}
回答by Ayano
ImageIO.write()
will compress the image by default - the compressed image has a smaller size but looks strange sometimes. I use BufferedOutputStream
to save the byte array data - this will keep the original image size.
ImageIO.write()
默认情况下会压缩图像 - 压缩后的图像尺寸较小,但有时看起来很奇怪。我BufferedOutputStream
用来保存字节数组数据 - 这将保持原始图像大小。
Here is the code:
这是代码:
import javax.xml.bind.DatatypeConverter;
import java.io.*;
public class ImageTest {
public static void main(String[] args) {
String base64String = "data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAHkAAAB5C...";
String[] strings = base64String.split(",");
String extension;
switch (strings[0]) {//check image's extension
case "data:image/jpeg;base64":
extension = "jpeg";
break;
case "data:image/png;base64":
extension = "png";
break;
default://should write cases for more images types
extension = "jpg";
break;
}
//convert base64 string to binary data
byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
String path = "C:\Users\Ene\Desktop\test_image." + extension;
File file = new File(path);
try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) {
outputStream.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
回答by Please_Dont_Bully_Me_SO_Lords
To decode:
解码:
byte[] image = Base64.getDecoder().decode(base64string);
To encode:
编码:
String text = Base64.getEncoder().encodeToString(imageData);