codename one image from url - java

I am trying to make a mobile app using Java and codename one plugin. My question is - what's the simples way to populate an image from a URL to a label? I Googled it and all I found was this piece of code:
Image i = URLImage.createToStorage(placeholder, "fileNameInStorage", "http://xxx/myurl.jpg", URLImage.RESIZE_SCALE);
But I have no idea how to use it. What is a placeholder? It asks an EncodedImage parameter, but if I do:
EncodedImage image = new EncodedImage(10, 10);
I get the error that EncodedImage is protected.
I simply want to populate an image from a URL to my desired label in a form.
I am using GUI builder.

The placeholder image is the image that should show while the image from URL is being downloaded and it's an EncodedImage.
If your Label already have an icon as a placeholder, you can use its icon, otherwise you can create a new placeholder image. Below are 3 options to create an EncodedImage and a URLImage usage example:
Method 1:
//generate a grey placeholder that matches the size of the label's icon
Image placeholder = Image.createImage(label.getIcon().getWidth(), label.getIcon().getWidth(), 0xbfc9d2);
EncodedImage encImage = EncodedImage.createFromImage(placeholder, false);
Method 2:
//Convert the label icon to EncodedImage
EncodedImage encImage = (EncodedImage)label.getIcon();
Method 3:
//Create a fresh grey EncodedImage when label doesn't have any icon set initially
int deviceWidth = Display.getInstance().getDisplayWidth();
Image placeholder = Image.createImage(deviceWidth / 10, deviceWidth / 10, 0xbfc9d2); //square image set to 10% of screen width
EncodedImage encImage = EncodedImage.createFromImage(placeholder, false);
Usage Example:
It's a good practice to use the URL as the cached image name in storage. If you have a multiple sizes of the same image, just prefix them with a unique string like "Large" + URL
label.setIcon(URLImage.createToStorage(encImage, "Medium_" + "http://xxx/myurl.jpg", "http://xxx/myurl.jpg", URLImage.RESIZE_SCALE));

Related

How to Maintain Aspect Ratio when Adding an Image to a PDFButtonFormField using iText7

I am collecting images from users with a form field on a PDF form. When the field is empty the user can populated the field in Acrobat and I can successfully read it from the form using iText7. If the user has previously uploaded an image, I want to present them with that image alreadyloaded into the form field and allow them to select and submit a different image. iText allows me to populate the form with the image but I distorts the image's aspect ration by resizing it to the dimensions of the form field's rectangle.
Is there a way to get iText's setImage() method to maintain the aspect ratio when loading the image?
I have also tried using the following code to modify the form field's rectangle to conform to the image aspect ratio before loading the image:
PdfReader reader = new PdfReader("TestForm.pdf");
ByteArrayOutputStream os = new ByteArrayOutputStream();
PdfWriter writer = new PdfWriter(os);
StampingProperties properties = new StampingProperties();
properties.useAppendMode();
PdfDocument document = new PdfDocument(reader, writer, properties);
PdfAcroForm acroForm = PdfAcroForm.getAcroForm(document, false);
acroForm.setNeedAppearances(true);
// get button form field
String fieldName = "Image1_af_image";
PdfButtonFormField field = (PdfButtonFormField)acroForm.getField(fieldName);
// retrieve widget rectangle
PdfDictionary widgets = field.getWidgets().get(0).getPdfObject();
com.itextpdf.kernel.geom.Rectangle rect = widgets.getAsRectangle(PdfName.Rect);
// modify its width
field.setImage("/Users/sschultz/Desktop/zuni logo.jpg").setFieldName(fieldName);
document.close();
os.flush();
os.close();
FileUtils.writeByteArrayToFile(new File("TestForm_out.pdf"), os.toByteArray());
but this code fails to modify the form field's original dimensions.
Finally, I have attempted to add a second, new form field with the appropriate aspect ratio:
// add second button field to form
String fieldName2 = "Image2_af_image";
PdfButtonFormField imageField = PdfFormField.createButton(document, new Rectangle(10, 10, 200, 50),
PdfButtonFormField.FF_PUSH_BUTTON);
imageField.setImage("image2.jpg").setFieldName(fieldName2);
acroForm.addField(imageField);
but the second field never appears in the form.
The default behavior of drawing button field appearance that doesn't preserve image's aspect ratio is quite complicated to override. Instead I can suggest to generate appearance manually, making it exactly as you want it.
// get widget dictionary
List<PdfWidgetAnnotation> widgets = pushButtonField.getWidgets();
PdfDictionary widgetDict;
if (widgets.size() > 0) {
widgetDict = widgets.get(0).getPdfObject();
} else {
// widgets.size() == 0 shouldn't really happen to properly created
// existing fields, but let's do it just in case
widgetDict = pushButtonField.getPdfObject();
}
Rectangle origRect = widgetDict.getAsRectangle(PdfName.Rect);
float borderWidth = pushButtonField.getBorderWidth();
String imgPath = ... // path to image file
// draw custom appearance preserving original field sizes
PdfFormXObject pdfFormXObject = new PdfFormXObject(new Rectangle(origRect.getWidth() - borderWidth * 2, origRect.getHeight() - borderWidth * 2));
Canvas canvas = new Canvas(pdfFormXObject, pdfDoc);
// Image class preserves aspect ratio by default
Image image = new Image(ImageDataFactory.create(imgPath))
.setAutoScale(true)
.setHorizontalAlignment(HorizontalAlignment.CENTER);
Div container = new Div()
.setMargin(borderWidth).add(image)
.setVerticalAlignment(VerticalAlignment.MIDDLE)
.setFillAvailableArea(true);
canvas.add(container);
canvas.close();
// override original appearance with new one
PdfDictionary apDict = new PdfDictionary();
widgetDict.put(PdfName.AP, apDict);
apDict.put(PdfName.N, pdfFormXObject.getPdfObject());
// mark widgetDict as modified in order to save its changes in append mode
widgetDict.setModified();
The last line (calling setModified()) is required to be done for all low level PdfObjects modifications if you are using properties.useAppendMode();. Otherwise the change will be not saved.

Can´t get absoluteX and absoluteY from image using itext

I try to get a image (jpg format) from url to put in my pdf using itext 5.0.5 with this simple code below:
Image imageToShow = null;
imageToShow = Image.getInstance(new URL("any image url here"));
imageToShow.scaleAbsolute(size[0], size[1]);
I get the image but the value from absoluteX and absoluteY is always a 'NaN' value and this problem prevents me to change this values (third line), what I'm doing wrong?
If you are in a situation where you can switch to another iText version, try out iText7.
The equivalent code would be:
// src url
String somePath = "https://www.pdfa.org/wp-content/uploads/2016/08/ITSC-Logo-Horizontal-RGB-300dpi.png";
// fetch image data
ImageData imageData = ImageDataFactory.create(new URL(somePath));
// turn into image object
Image image = new Image(imageData);
// perform scaling operation
image = image.scaleAbsolute(120f, 120f);
// debug
System.out.println(image.getImageWidth() + "x" + image.getImageHeight());

Relative path using setImageResource

I am trying to display an image in my app that changes everytime I press a button.
The name of the image that should be shown is in my object. I can get the name of the image with
String nameOfImage = myObhect.get(i).getImageName();
Now, I want to display the current image with
iv.setImageResource(R.drawable.notruf);
Using setImageResource , I don´t know how to bring the name of my image in setImageResource because, for example
iv.setImageResource(R.drawable. + aktbild) isn´t possible for sure.
I also tried the way with setImageDrawable but that does not work for me.
I use similar solution in my application :
Context mContext = this; // I supposed you're in Activity
String imgName = fragenkatalog.get(i).getBild();
int resId = mContext.getResources().getIdentifier(imgName,
"drawable", mContext.getApplicationInfo().packageName);
if(resId > 0){
iv.setImageResource(resId);
}
I believe that this code will help u..
String aktbild = fragenkatalog.get(i).getBild();
byte[] decodedString = Base64.decode(aktbild , Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
After that, if you want to resize that image use this code.
int width=75;
int height=75;
Bitmap resizedbitmap=Bitmap.createScaledBitmap(decodedByte, width, height, true);
finally set image into ImageView.
Icon.setImageBitmap(resizedbitmap);`

Swing - Get URL used by ImageProducer to produce an Image

I am trying to get to the url of an Image.
Icon icon = getIcon(); // gets a previously initialised Icon
ImageIcon imageIcon = (ImageIcon) icon;
Image image = imageIcon.getImage();
image.getSource(); // returns a java.awt.image.FilteredImageSource
The FilteredImageSource has a property src, which contains the url of the image.
However the src property is with default access modifier.
Is there any way I can get the image url at this point in time ?

abnormal resizing of java.awt.Image on using getImage() and getScaledInstance()

I m making a java rmi based application where i pass and receive an ImageIcon object from the server...
(the image is stored in a separate URL in server)
The function involves the following....
1. Getting the image from the server at first....(on button press A)
2. Replacing it with a image file in the client[optional]....(on button press B)
3. Remove the image with a default image[optional]....(on button press C)
4. Sending it back to the Server....................(On button press D).....
Here the image is displayed in ajlabel calledimg_label
The codes i've used are as follows.....
Variables used
java.awt.Image img;
javax.swing.ImageIcon CurrentImageIcon;
javax.swing.ImageIcon DefaultImageIcon;
// CurrentImageIcon contains the image to be displayed in the img_label....
// img is used for copying as well for scaling......
// DefaultImageIcon holds the default Image......
On Button Press A
img = temp.getImage();
CurrentImageIcon = new ImageIcon(img);
// Assuming temp holds the ImageIcon taken from the server.......
img=img.getScaledInstance(83,85 , Image.SCALE_DEFAULT);
img_label.setIcon(new ImageIcon(img));
img_label.revalidate();
img_label.repaint();
On Button Press B
String url_text = jTextField.getText(); // taking the url frm the field.....
CurrentImageIcon = new ImageIcon(url_text);
img=CurrentImageIcon.getImage();
img=img.getScaledInstance(83,85 , Image.SCALE_DEFAULT);
img_label.setIcon(new ImageIcon(img));
img_label.revalidate();
img_label.repaint();
On Button Press C
img = DefaultImageIcon.getImage();
CurrentImageIcon = new ImageIcon(img);
img=img.getScaledInstance(83,85 , Image.SCALE_DEFAULT);
img_label.setIcon(new ImageIcon(img));
img_label.revalidate();
img_label.repaint();
On Button Press D
// ImagetoSend is an ImageIcon to be sent to the Server.....
ImagetoSend = CurrentImageIcon;
CurrentImageIcon = null;
Now the problem i m getting is a weird one......
The image is getting embedded as i wanted on repainting when i click this button........
But when i download the recently uploaded image next time on Button press A....it is displayed either magnified or reduced to size even though i included the getScaledInstance method....
like this...
The image i am handling is a jpg image....
I even checked the image at Server directory.....No size change has occured on that file which was uploaded from client to server. But the change is observed when it is downloaded and embedded to the jlabel...
Can Anyone help me to sort out this issue...??
Somehow it is getting scaled down twice. Either you scale it down then send it to the server where it is scaled down, or the both button clicks scale it. Eliminate the scale down code on the server side and see what happens.

Categories