3

I have a question about using Javonet. In the .NET code I have a method that returns a System.DrawingImage and I have to obtain it on my Java side of code. So when I issue a "get" of the attribute by Javonet API, it returns an NObject. Here is the example:


.NET code:


...
namespace ImageTest
{
    public class FileReader
    {
        public byte[] GetByteArray(string filename)
        {
            return System.IO.File.ReadAllBytes(filename);
        }

        public System.Drawing.Image GetImage(string filename)
        {
            byte[] b = GetByteArray(filename);
            using (var ms = new System.IO.MemoryStream(b, false))
            {
                return Image.FromStream(ms);
            }
        }
    }
}

Java code


...
public Image getImage(String fileName) {
    NObject res = null;
    try {
       res = item.get(propName); // Casting NObject to Image is not allowed!
    } catch (JavonetException jex) {
       jex.printStackTrace(); 
    }
    return res; // Wrong: an Image object must be returned!
}

I have to cast 'res' to Image or ImageIcon or something similar in Java. Any suggestion? Have I to get it as byte array or something else or there is another mechanism on Javonet?

Shog9
  • 156,901
  • 35
  • 231
  • 235
Andrea Annibali
  • 379
  • 2
  • 5

1 Answers1

2

Any complex object (like class) will always be returned in form of "NObject" so in fact it is the handle to that object on .NET side. If you want to move the concrete image from .NET to Java you need to do it using the value-types so in form of byte[] or string base64 as there is no direct counterpart of "System.Drawing.Image" class in Java.

Therefore you just need to extract the value-type form of your image from System.Drawing.Image class.

You can do it like this:

NObject ms = Javonet.New("MemoryStream");
yourImageNObject.Save(ms,Javonet.getType("System.Drawing.Imaging.ImageFormat").getRef("Jpeg"));
Byte[] imageBytes = ms.invoke("ToArray");

//you can also unbox the bytes to regular byte[]
byte[] unboxed = new byte[fileBytes.length];

for(int i=0; i<imageBytes.length;i++)
    unboxed[i]=imageBytes[i].byteValue();