Scale image with Vaadin and Java - java

I have following code to upload an image and show it on the webpage
// Show uploaded file in this placeholder
final Embedded image = new Embedded("Uploaded Image");
image.setVisible(false);
// Implement both receiver that saves upload in a file and
// listener for successful upload
class ImageUploader implements Receiver, SucceededListener {
public File file;
public OutputStream receiveUpload(String filename, String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
try {
// Open the file for writing.
file = new File(tmp_dir + "/" + filename);
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
return null;
}
return fos; // Return the output stream to write to
}
public void uploadSucceeded(SucceededEvent event) {
// Show the uploaded file in the image viewer
image.setVisible(true);
image.setSource(new FileResource(file));
}
};
ImageUploader receiver = new ImageUploader();
// Create the upload with a caption and set receiver later
Upload upload = new Upload("Upload Image Here", receiver);
upload.setButtonCaption("Start Upload");
upload.addSucceededListener(receiver);
final FormLayout fl = new FormLayout();
fl.setSizeUndefined();
fl.addComponents(upload, image);
The problem is, it shows the full resolution and I want to scale (so it remains proportional) it down to 180px width. The picture also needs to be saved as the original filename_resized.jpg but I can't seem to get it to scale. Several guides on the web talk about resizing (but then the picture gets distorted) or it gives some issues with Vaadin.
Update:
Added the scarl jar (from this answer)) because it would be easy-peasy then by using following code:
BufferedImage scaledImage = Scalr.resize(image, 200);
but that gives following error:
The method resize(BufferedImage, int, BufferedImageOp...) in the type Scalr is not applicable for the arguments (Embedded, int)
and I cannot cast because Cannot cast from Embedded to BufferedImage error
Update: with following code I can cast to the right type
File imageFile = (((FileResource) (image.getSource())).getSourceFile());
BufferedImage originalImage = ImageIO.read(imageFile) ;
BufferedImage scaledImage = Scalr.resize(originalImage, 200);
but now I can't show the image..
final FormLayout fl = new FormLayout();
fl.setSizeUndefined();
fl.addComponents(upload, scaledImage);
because of error The method addComponents(Component...) in the type AbstractComponentContainer is not applicable for the arguments (Upload, BufferedImage)

You cannot use Vaadin objects directly with a third-party tool such as Scalr without adapting one to the other. "Embedded" is a Vaadin class whereas SclaR expects a "BufferedImage".
So, you first need to extract the File object from the Embedded object:
File imageFile = ((FileResource)(image.getSource()).getSourceFile();
Then, load it into the BufferedImage using ImageIO, such as explained in the link you pointed at ( What is the best way to scale images in Java? )
BufferedImage img = ImageIO.read(...); // load image
Then, you have the BufferedImage object you were looking for.

Related

Image/File upload path after making app in Java from Eclipse

I am making a Java-SQL database storing app on Eclipse and MySQL. In this app, I have to upload image to the file directory. Currently while making this app, I am using an image upload path and storing all the uploaded images there. But when I'm finished with the app, and if I'm to work it on someone else's computer the image upload path in the code obviously will not work on that computer. What shall I do to make it work on other computer as well? Should I make a prompt which asks for image upload path every time the app opens and store that, or something else?? please help.
private String imageUploadPath = "/home/tsoprano/Documents/eclipse-workspace/enable/src/com/enable/regis/imgupload/";
File file1;
picLabel = new JLabel(" Upload Photo");
picLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
JFileChooser imageChooser= new JFileChooser();
if(imageChooser.showOpenDialog(picLabel)==JFileChooser.APPROVE_OPTION) {
file1 = imageChooser.getSelectedFile();
ImageIcon icon= new ImageIcon(imageChooser.getSelectedFile().getPath());
Image img=icon.getImage().getScaledInstance(130, 150, Image.SCALE_SMOOTH);
icon= new ImageIcon(img);
picLabel.setIcon(icon);
}
}
});
//inside the submit button action
String filePath = imageUploadPath + file1.getName();
try {
BufferedImage bi = ImageIO.read(file1);
ImageIO.write(bi, "jpg", new File(filePath));
} catch (IOException e1) {
e1.printStackTrace();
}
rdto.setPicUrl(filePath);
I would not suggest doing this via a config file, because this is not very user-friendly. Instead, get the current directory (i. e. the one that you executed the java command) using System.getProperty("user.dir"). Then create a new folder inside there, and use it as your upload folder. This will make sure you always have a useable path without bothering the user with specifying it.

i am not able to get the images read in java for exporting it as JAR

This code throws a NullPointerException and I have no idea why.
try {
imageIcon = new ImageIcon(ImageIO.read(new File("res/Background.png")));
backgroundImage = imageIcon.getImage();
signIn = new MyButton("SignIn", ImageIO.read(new File("res/SignIn.png")), ImageIO.read(new File("res/SignInHover.png")));
signUp = new MyButton("SignUp", ImageIO.read(new File("res/SignUp.png")), ImageIO.read(new File("res/SignUpHover.png")));
back = new MyButton("Back", ImageIO.read(new File("res/Back.png")), ImageIO.read(new File("res/BackHover.png")));
exit = new MyButton("Exit", ImageIO.read(new File("res/Exit.png")), ImageIO.read(new File("res/ExitHover.png")));
} catch(IOException e) {
JOptionPane.showMessageDialog(null, "");
}
res/ is a source folder in the project root which contains all images used in this piece of code but I'm not able to get it to work. I've tried using getClass().getResource() (which works from inside Eclipse but not from a .jar file) and getClass().getResourceAsStream() (which throws an exception telling that the input stream is null) but to no avail.
P.S.: MyButton is a user-defined class which extends JButton and has a constructor MyButton(String, final BufferedImage, final BufferedImage).
After all I succeeded by just making images folder under my source(i.e. under res) folder. And using method
ImageIO.read(getClass().getResource("/images/SignIn.png"));

Download to folder/files android apps

my problem is that I use in my practice are pdf files. I did not add them into my application. I want pdf files from ftp or a URL to download it. I have no idea about the solution. I've tried a lot ftp code and URL code. All I want, when you pressed the button of the sdcard files from a URL or FTP address to get a download. Thanks for your help.
this code is working for me
public void onClick(View v) {
PrintAttributes printAttrs = new PrintAttributes.Builder().
setColorMode(PrintAttributes.COLOR_MODE_COLOR).
setMediaSize(PrintAttributes.MediaSize.NA_LETTER).
setResolution(new PrintAttributes.Resolution("zooey", PRINT_SERVICE, 300, 300)).
setMinMargins(PrintAttributes.Margins.NO_MARGINS).
build();
PdfDocument document = new PrintedPdfDocument(DynamicPDFHelloWorld.this, printAttrs);
// crate a page description
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(300, 300, 1).create();
// create a new page from the PageInfo
PdfDocument.Page page = document.startPage(pageInfo);
// repaint the user's text into the page
View content = findViewById(R.id.textarea);
content.draw(page.getCanvas());
content.draw(edt.getText().toString().);
// do final processing of the page
document.finishPage(page);
// Here you could add more pages in a longer doc app, but you'd have
// to handle page-breaking yourself in e.g., write your own word processor...
// Now write the PDF document to a file; it actually needs to be a file
// since the Share mechanism can't accept a byte[]. though it can
// accept a String/CharSequence. Meh.
try {
File f = new File(Environment.getExternalStorageDirectory().getPath() + "/pruebaAppModerator.pdf");
FileOutputStream fos = new FileOutputStream(f);
document.writeTo(fos);
document.close();
fos.close();
} catch (IOException e) {
throw new RuntimeException("Error generating file", e);
}
}
});

How to load Images from a package in java

I usually use this to load from the same package
Image image;
String img = "image.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(img));
image = i.getImage();
How can I load an image from a package specified for images?
You can try any one
// Read from same package
ImageIO.read(getClass().getResourceAsStream("c.png"));
// Read from absolute path
ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\c.png"));
// Read from images folder parallel to src in your project
ImageIO.read(new File("images\\c.jpg"));
Use
ImageIcon icon=new ImageIcon(<any one from above>);
You can use BufferedImage also in place of ImageIcon directly.
For more information read it here How to retrieve image from project folder?
Image image;
String img = "image.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(img));
image = i.getImage();
Suggests that "image.png" resides within the same package as the class represented by this
You can use absolute paths to reference resources that reside within different packages
String img = "/path/to/images/image.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(img));
The important concept here is to understand that the path is suffixed to class path
Personally, you should be using ImageIO over ImageIcon, apart from supporting more formats, it throws an IOException when something goes wrong and is guaranteed to return a fully loaded image (when successful).
See How to read images for more details
You don't need to use(like "this") locally: this.getClass().getResource( img );
Just use class loader globally : ClassLoader.getSystemResource( path );
I'm gonna show you my library function below
public final class PackageResourceLoader {
// load image icon
public static final ImageIcon loadImageIcon( final String path ) {
final URL res = ClassLoader.getSystemResource( path );
return new ImageIcon( res );
}
// load buffered image
public static final BufferedImage loadBufferedImage( final String path ) {
final URL res = ClassLoader.getSystemResource( path );
try { return ImageIO.read( res ); }
catch( final Exception ex ) { return null; }
}
}
if your img.png is in package pack use PackageResourceLoader.loadImageIcon( "pack/img.png" );

Cant Load Image on Java (BlueJ)

Im Trying to load my images on to Java but when running the code nothing appears inside my JFrame.
The way im doing it is calling my Image function from my main:
import java.awt.*; // Graphics stuff from the AWT library, here: Image
import java.io.File; // File I/O functionality (for loading an image)
import javax.swing.ImageIcon; // All images are used as "icons"
public class GameImage
{
public static Image loadImage(String imagePathName) {
// All images are loades as "icons"
ImageIcon i = null;
// Try to load the image
File f = new File(imagePathName);
if(f.exists()) { // Success. Assign the image to the "icon"
i = new ImageIcon(imagePathName);
}
else { // Oops! Something is wrong.
System.out.println("\nCould not find this image: "+imagePathName+"\nAre file name and/or path to the file correct?");
System.exit(0);
}
// Done. Either return the image or "null"
return i.getImage();
} // End of loadImages method
}
And then calling it here:
GI_Background = GameImage.loadImage("Images//background.jpg");
GI_DuskyDolphin = GameImage.loadImage("Images//DuskyDolphin.jpg");
If this is not enough information I'll gladly supply the rest of the code :)
Thanks
If the image is part of the application, do not use a File but use the java resource mechanism.
URL imageUrl = getClass().getResource("/Images/background.jpg");
return new ImageIcon(imageURL).getImage();
The resource URL will return null when not found.
If the application is packed in a .jar, you can open that with 7zip/WinZip or so, and check the path. It must be case-sensitive, and using / (not backslash).
I'm not quite sure what you try to achieve...
to load an image with a method, this will be enough:
private Image loadImage(String fileName){
return (new ImageIcon(fileName)).getImage();
}
Afterwards, i would create a JLabel with the Image as background;
ImageIcon image = getImage( filename );
JLabel imageLabel = new JLabel( image );
imageLabel.setSize( image.getIconHeight, image.getIconWidth );
JFrame frame = new JFrame();
frame.add( imageLabel );
Try this and feel free to aks again if i does not work for you, or thats not want you want :)

Categories