I'm trying to create a URL image from a imgur png with codenameone, using this code:
Form hi = new Form(new BoxLayout(BoxLayout.Y_AXIS));
EncodedImage placeholder = EncodedImage.createFromImage(Image.createImage(hi.getWidth(), hi.getWidth() / 5, 0xffff0000), true);
URLImage background = URLImage.createToStorage(placeholder, "test2.png","https://i.imgur.com/VMwUrqH.png", URLImage.RESIZE_SCALE_TO_FILL);
background.fetch();
hi.add(background);
hi.show();
But it just gives me this error:
Exception: java.lang.IllegalArgumentException - create image failed for the given image data of length: 7165
The given file is a valid PNG image data, 512 x 566, 8-bit/color RGBA, non-interlaced. It should work fine with Codename One, but it's not so. Your code gives me your same exception.
Indeed, the file downloaded by Codename One is completely different from the file that we can download from a browser. Codename One downloads a file that is a (valid?) PNG image data, 1080 x 216, 8-bit/color RGBA, non-interlaced. I suspect the server is applying a redirect to avoid automatic downloads like this one.
To confirm my hypothesis, I changed the user-agent of Codename One, assigning it the same one of my browser:
ConnectionRequest.setDefaultUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0");
The result is that it works! :-)
However, to force Codename One to re-download the file with the given user-agent, you must delete the test2.png
file from the .cn1
directory.
This is the full working code:
Form hi = new Form(new BoxLayout(BoxLayout.Y_AXIS));
ConnectionRequest.setDefaultUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0");
EncodedImage placeholder = EncodedImage.createFromImage(Image.createImage(hi.getWidth(), hi.getWidth() / 5, 0xffff0000), true);
URLImage background = URLImage.createToStorage(placeholder, "test2.png", "https://i.imgur.com/VMwUrqH.png", URLImage.RESIZE_SCALE_TO_FILL);
background.fetch();
hi.add(background);
hi.show();
User contributions licensed under CC BY-SA 3.0