SWT图像到/从字符串 [英] SWT Image to/from String
本文介绍了SWT图像到/从字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将SWT图像转换为字符串,反之亦然:
I am trying to convert an SWT Image to String and vice versa:
To String:
To String:
Display display = new Display();
final Image image = new Image(display, "c:\test.png");
// Looks good
showImage(image ,600,400);
ImageData imageData = testImage.getImageData();
byte[] data = imageData.data;
String imageString = new String(Base64.encode(data));
返回图片:
byte[] decode = Base64.decode(imageString.getBytes());
decode.toString();
Image c_img = new Image(Display.getCurrent(), stringToInputStream(decode.toString()));
// Throws exception.
showImage(c_image ,600,400);
其中:
private static void showImage(final Image image, int w, int h) {
Display display = new Display();
Shell shell = new Shell(display, SWT.SHELL_TRIM | SWT.DOUBLE_BUFFERED);
shell.setLayout(new FillLayout());
shell.addListener(SWT.Paint, new Listener() {
public void handleEvent(Event e) {
GC gc = e.gc;
int x = 10, y = 10;
gc.drawImage(image, x, y);
gc.dispose();
}
});
shell.setSize(w, h);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
if (image != null && !image.isDisposed()) {
image.dispose();
}
display.dispose();
}
private static InputStream stringToInputStream(String input) {
InputStream is = null;
try {
is = new ByteArrayInputStream(input.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return is;
}
从String中显示图像时出错:
The error when showing the image from String is:
org.eclipse.swt.SWTException: Unsupported or unrecognized format
at org.eclipse.swt.SWT.error(SWT.java:4083)
at org.eclipse.swt.SWT.error(SWT.java:3998)
at org.eclipse.swt.SWT.error(SWT.java:3969)
at org.eclipse.swt.internal.image.FileFormat.load(FileFormat.java:82)
at org.eclipse.swt.graphics.ImageLoader.load(ImageLoader.java:130)
at org.eclipse.swt.graphics.ImageDataLoader.load(ImageDataLoader.java:22)
at org.eclipse.swt.graphics.ImageData.<init>(ImageData.java:331)
at org.eclipse.swt.graphics.Image.<init>(Image.java:545)
我是第一个到做这个?或者是否有一些例子说明如何正确地完成这项工作?
Am I the first to do this? Or are there some examples showing how this should be done properly?
推荐答案
当然这是错误的:
stringToInputStream(decode.toString())
如果在字节数组上调用 toString()
,则不会将字节转换为 String
;你得到一个 String
看起来像
If you call toString()
on a byte array, you don't get the bytes converted to a String
; you get a String
that looks like
byte[@6536753
你需要从解码构建 ByteArrayInputStream
本身。
You need to construct the ByteArrayInputStream
from "decode" itself.
这篇关于SWT图像到/从字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文