SWT图像到/从字符串

时间:2011-05-31 14:23:16

标签: java image swt

我正在尝试将SWT图像转换为字符串,反之亦然:

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显示图像时出错:

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)

我是第一个这样做的吗?或者是否有一些例子说明如何正确地完成这项工作?

3 个答案:

答案 0 :(得分:4)

当然这是错误的:

stringToInputStream(decode.toString())

如果在字节数组上调用toString(),则不会将字节转换为String;你得到的String看起来像

byte[@6536753

您需要从“解码”本身构建ByteArrayInputStream

答案 1 :(得分:0)

为什么你用String操作?字节[]对你不好吗?你在转换它的操作中添加了无用的步骤。

答案 2 :(得分:0)

If someone needs it, I have achieved it with help of this link: http://www.programcreek.com/2009/02/java-convert-image-to-byte-array-convert-byte-array-to-image/

After a lot of tries, using the suggested approach of the question, or also using ImageLoader, I was always getting:

org.eclipse.swt.SWTException: Unsupported or unrecognized format

But with the approach of the link (using Base64.decode and encode) it works.