Java - XML 中的图像编码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1312832/
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
Java - Image encoding in XML
提问by Hoopla
I thought I would find a solution to this problem relatively easily, but here I am calling upon the help from ye gods to pull me out of this conundrum.
我以为我会相对容易地找到解决这个问题的方法,但在这里我呼吁各位大神帮助我摆脱这个难题。
So, I've got an image and I want to store it in an XML document using Java. I have previously achieved this in VisualBasic by saving the image to a stream, converting the stream to an array, and then VB's xml class was able to encode the array as a base64 string. But, after a couple of hours of scouring the net for an equivalent solution in Java, I've come back empty handed. The only success I have had has been by:
所以,我有一个图像,我想使用 Java 将它存储在一个 XML 文档中。我以前在 VisualBasic 中通过将图像保存到流,将流转换为数组,然后 VB 的 xml 类能够将数组编码为 base64 字符串来实现这一点。但是,在网上搜索了几个小时的 Java 等效解决方案后,我空手而归。我唯一的成功是:
import it.sauronsoftware.base64.*;
import java.awt.image.BufferedImage;
import org.w3c.dom.*;
...
BufferedImage img;
Element node;
...
java.io.ByteArrayOutputStream os = new java.io.ByteArrayOutputStream();
ImageIO.write(img, "png", os);
byte[] array = Base64.encode(os.toByteArray());
String ss = arrayToString(array, ",");
node.setTextContent(ss);
...
private static String arrayToString(byte[] a, String separator) {
StringBuffer result = new StringBuffer();
if (a.length > 0) {
result.append(a[0]);
for (int i=1; i<a.length; i++) {
result.append(separator);
result.append(a[i]);
}
}
return result.toString();
}
Which is okay I guess, but reversing the process to get it back to an image when I load the XML file has proved impossible. If anyone has a better way to encode/decode an image in an XML file, please step forward, even if it's just a link to another thread that would be fine.
我想这是可以的,但是在我加载 XML 文件时逆转该过程以将其恢复为图像已被证明是不可能的。如果有人有更好的方法来编码/解码 XML 文件中的图像,请继续前进,即使它只是指向另一个线程的链接也可以。
Cheers in advance,
提前加油,
Hoopla.
呼啦啦。
采纳答案by Jo?o Silva
I've done something similar (encoding and decoding in Base64) and it worked like a charm. Here's what I think you should do, using the class Base64
from the Apache Commons project:
我做过类似的事情(在 Base64 中编码和解码),它的作用就像一个魅力。以下是我认为您应该使用Base64
Apache Commons 项目中的类执行的操作:
// ENCODING
BufferedImage img = ImageIO.read(new File("image.png"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "png", baos);
baos.flush();
String encodedImage = Base64.encodeToString(baos.toByteArray());
baos.close(); // should be inside a finally block
node.setTextContent(encodedImage); // store it inside node
// DECODING
String encodedImage = node.getTextContent();
byte[] bytes = Base64.decode(encodedImage);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
Hope it helps.
希望能帮助到你。
回答by Eric Anderson
回答by Michael Borgwardt
Your arrayToString()
method is rather bizarre (what's the point of that separator?). Why not simply say
你的arrayToString()
方法很奇怪(那个分隔符有什么意义?)。为什么不简单地说
String s = new String(array, "US-ASCII");
The reverse operation is
反向操作是
byte[] array = s.getBytes("US-ASCII");
Use the ASCII encoding, which should be sufficient when dealing with Base64 encoded data. Also, I'd prefer a Base64 encoder from a reputable source like Apache Commons.
使用 ASCII 编码,在处理 Base64 编码数据时应该足够了。另外,我更喜欢来自像 Apache Commons 这样的知名来源的 Base64 编码器。
回答by Clint
After you get your byte array
获得字节数组后
byte[] array = Base64.encode(os.toByteArray());
use an encoded String :
使用编码字符串:
String encodedImg = new String( array, "utf-8");
Then you can do fun things in your xml like
然后你可以在你的 xml 中做一些有趣的事情,比如
<binImg string-encoding="utf-8" bin-encoding="base64" img-type="png"><![CDATA[ encodedIImg here ]]></binImg>
回答by Thorbj?rn Ravn Andersen
The basic problem is that you cannot have an arbitrary bytestream in an XML document, so you need to encode it somehow. A frequent encoding scheme is BASE64, but any will do as long as the recipient knows about it.
基本问题是您不能在 XML 文档中拥有任意字节流,因此您需要以某种方式对其进行编码。常用的编码方案是 BASE64,但只要接收者知道它,任何编码方案都可以。
回答by ZZ Coder
You don't need to invent your own XML data type for this. XML schema defines standard binary data types, such as base64Binary, which is exactly what you are trying to do.
您不需要为此发明自己的 XML 数据类型。XML 模式定义了标准的二进制数据类型,例如base64Binary,这正是您想要做的。
Once you use the standard types, it can be converted into binary automatically by some parsers (like XMLBeans). If your parser doesn't handle it, you can find classes for base64Binary in many places since the datatype is widely used in SOAP, XMLSec etc.
一旦使用了标准类型,它就可以被一些解析器(如 XMLBeans)自动转换为二进制文件。如果您的解析器不处理它,您可以在许多地方找到 base64Binary 的类,因为该数据类型广泛用于 SOAP、XMLSec 等。
回答by vocaro
With Java 6, you can use DatatypeConverter to convert a byte array to a Base64 string:
在 Java 6 中,您可以使用 DatatypeConverter 将字节数组转换为 Base64 字符串:
byte[] imageData = ...
String base64String = DatatypeConverter.printBase64Binary(imageData);
And to convert it back:
并将其转换回来:
String base64String = ...
byte[] imageData = DatatypeConverter.parseBase64Binary(base64String);
回答by Vishesh
most easy implementation I was able to made is as below, And this is from Server to Server XML transfer containing binary data Base64 is from the Apache Codec library: - Reading binary data from DB and create XML
我能够实现的最简单的实现如下,这是从服务器到服务器的 XML 传输,其中包含二进制数据 Base64 来自 Apache 编解码器库: - 从数据库读取二进制数据并创建 XML
Blob blobData = oRs.getBlob("ClassByteCode"); byte[] bData = blobData.getBytes(1, (int)blobData.length()); bData = Base64.encodeBase64(bData); String strClassByteCode = new String(bData,"US-ASCII");
Blob blobData = oRs.getBlob("ClassByteCode"); byte[] bData = blobData.getBytes(1, (int)blobData.length()); bData = Base64.encodeBase64(bData); String strClassByteCode = new String(bData,"US-ASCII");
- on requesting server read the tag and save it in DB
- 在请求服务器上读取标签并将其保存在数据库中
byte[] bData = strClassByteCode.getBytes("US-ASCII"); bData = Base64.decodeBase64(bData); oPrStmt.setBytes( ++nParam, bData );
byte[] bData = strClassByteCode.getBytes("US-ASCII"); bData = Base64.decodeBase64(bData); oPrStmt.setBytes( ++nParam, bData );
easy as it can be.. I'm still working on implementing the streaming of the XML as it is generated from the first server where the XML is created and stream it to the response object, this is to take care when the XML with binary data is too large.
尽可能简单......我仍在努力实现 XML 的流式传输,因为它是从创建 XML 的第一台服务器生成的,并将其流式传输到响应对象,这是在 XML 与二进制数据太大。
- Vishesh Sahu
- 维舍什·萨胡
回答by Alex Spencer
I know that the question was aking how to encode an image via XML, but it is also possible to just stream the bytes via an HTTP GET request instead of using XML and encoding an image. Note that input is a FileInputStream
.
Server Code:
我知道问题是关于如何通过 XML 对图像进行编码,但也可以仅通过 HTTP GET 请求流式传输字节,而不是使用 XML 并对图像进行编码。请注意,输入是一个FileInputStream
. 服务器代码:
File f = new File(uri_string);
FileInputStream input = new FileInputStream(f);
OutputStream output = exchange.getResponseBody();
int c = 0;
while ((c = input.read()) != -1) {
output.write(c); //writes each byte to the exchange.getResponseBody();
}
result = new DownloadFileResult(int_list);
if (input != null) {input.close();}
if (output != null){ output.close();}
Client Code:
客户代码:
InputStream input = connection.getInputStream();
List<Integer> l = new ArrayList<>();
int b = 0;
while((b = input.read()) != -1){
l.add(b);//you can do what you wish with this list of ints ie- write them to a file. see code below.
}
Here is how you would write the Integer list to a file:
以下是将整数列表写入文件的方法:
FileOutputStream out = new FileOutputStream("path/to/file.png");
for(int i : result_bytes_list){
out.write(i);
}
out.close();
回答by Frizz1977
node.setTextContent( base64.encodeAsString( fileBytes ) )
using org.apache.commons.codec.binary.Base64
使用 org.apache.commons.codec.binary.Base64