how to retriev image from project dir to jlabel? - java

I am new user to java netbeans 8. I want to insert employee to sql server DB. I use a jlabel to display selected image and the jlabel has its local background of user. The BG store in src, in the src, I create Image folder and inside Image folder, I have folder named 24. inside the 24 folder, I store my bg image namce employeebg.png.
I need after inserted, all texts are clear and the jlabel/lbpicture back to employeebg.png.
I use this code.
private String getpath=null;
private byte[] image=null;
private File opt=null;
private FileInputStream FIS;
try{
getpath = "\\Image\\24\\employeebg.png";
opt = new File(getpath);
FIS=new FileInputStream(opt);
ByteArrayOutputStream array = new ByteArrayOutputStream();
byte[] imagedata=new byte[1024];
for(int readnum;(readnum = FIS.read(imagedata)) !=-1;){
array.write(imagedata,0,readnum);
}
image = array.toByteArray();
format = new ImageIcon(array.toByteArray());
Image img = format.getImage().getScaledInstance(lbpicture.getWidth(),lbpicture.getHeight(),Image.SCALE_SMOOTH);
ImageIcon imgicon=new ImageIcon(img);
lbpicture.setIcon(imgicon);
}catch(Exception e){
e.printStackTrace();
}
what is the best way to done this?
Thank you in advance.

I think You should get your images from the classpath:
...
try{
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Image image = ImageIO.read(cl.getResource("/Image/24/employeebg.png"));
Image img = image.getScaledInstance(lbpicture.getWidth(),lbpicture.getHeight(),Image.SCALE_SMOOTH);
ImageIcon imgicon=new ImageIcon(img);
lbpicture.setIcon(imgicon);
}catch(Exception e){
e.printStackTrace();
}
...
UPDATE
To add resources to your netbeans project, create a directory "resources" in the root of your project; then add it as a source package folder as follows:
right-click on your project in the Project explorer, select "Properties in the drop down menu,
In categories "Sources", click on the "Add folder..." button at the right of the "Source Package folders" list, and select the "resources" folder you've just created,
Click "OK",
Move your folder "Image" into the "resources" folder.

Related

Java application saves image on project folder instead of eclipse folder

I'm trying to save an image file to my project folder.
Image file comes from database.
It is a maven project and rest web service.
I don't have any servlets.
Here is my code, but it saves on eclipse folder.
byte[] imgData = null;
Blob img = null;
img = resultset.getBlob("LOGO");
imgData = img.getBytes(1, (int) img.length());
BufferedImage img2 = null;
img2 = ImageIO.read(new ByteArrayInputStream(imgData));
File outputfile = new File("birimler/"+resultset.getString("BASLIK")
+ "Logo.png");
outputfile.mkdirs();
ImageIO.write(img2, "png", outputfile);
System.out.println(outputfile.getAbsolutePath());
Output is: /Users/xxx/Documents/eclipse/Eclipse.app/Contents/MacOS/birimler/imageLogo.png
Thanks for help!
Thats because eclipse working dir is his installation folder.
Provide a full absolute path, or change the working dir of your run configuration.
File outputfile = new File("/birimler/"+resultset.getString("BASLIK")
+ "Logo.png");
Would end up in
"/birimler/imageLogo.png"
And adding one more slash:
File outputfile = new File("/birimler/"+resultset.getString("BASLIK")
+ "/Logo.png");
would produce:
"/birimler/image/Logo.png"

How to save an image received through network in java

image is successfully received at the server side and I can display it on label
but my Problem is how to save that image
I have used
JFileChooser.showSaveDialog()
I tried printstream. I can save the file but whenever I opened the file in image viewer it is showing as this type of file is cant be opened
BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(sock.getInputStream()));
System.out.println("Image received!!!!");
JFileChooser fc = new JFileChooser();
int i=fc.showSaveDialog(null);
if( i == JFileChooser.APPROVE_OPTION ) {
PrintStream ps = new PrintStream(fc.getSelectedFile());
// ImageIO.write(bimg,"JPG",fc.getInputStream());
ps.print( img);
ps.close();
lblNewLabel.setIcon(new ImageIcon(img)); //image is successfully displaying on the label
}
You're writing the "object" representation of the image, only if your load it through PrintStream would you have a chance of seeing it again.
Try using something like...
ImageIO.write(img,"JPG",fc.getSelectedFile());
instead

Drawing a resource image on to a buffered image

Okay, I want to create a copy of an image I have in my resource folder, and put it onto the desktop pretty much. Example: My project has a resource folder with an image called apple.png. Since when I export my jar file it can't find it, I want to copy it to the desktop so it can find it from there. Here is what I tried doing:
try {
// retrieve image
BufferedImage bi = new BufferedImage(256, 256,
BufferedImage.TYPE_INT_RGB);
File outputfile = new File(
"C:/Users/Owner/Desktop/saved.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
}
}
This just created the buffered Image for me on my desktop. How do I take my res Image and copy it to it.
Any reason for loading it as an image? If you just want to copy resource to desktop without changing it:
InputStream resStream = getClass().getResourceAsStream("/image.png"));
//Improved creation of output path:
File path = new File(new File(System.getProperty("user.home")), "Desktop");
File outputFile = new File(path, "saved.png");
//now write it
Files.copy(resStream, outputFile);
You need to load the BufferedImage as the image file.
BufferedImage bi = ImageIO.read(new File(getClass().getResource("/apple.png"));));
All the other steps are the same.

Java getClass().getResource on a png returning Null Pointer

I am not sure if I am referring to the right location with this code, the images I am trying to access are titled Flower0.png etc.
They are located in the same directory as the rest of my code for this project.
This class is in a src folder called hangman.ui and the .png files are located in a directory folder called Resources.
Perhaps getClass().getResource is not right?
This is my first time trying to put images into a GUI.
Help is much appreciated!
public WiltingFlowerRendererRemix(HangmanLogic logic)
{
panel = new JPanel();
panel.setLayout(new BorderLayout());
imageLabel = new JLabel();
panel.add(imageLabel, BorderLayout.CENTER);
int numberOfImages = 10;
images = new ImageIcon[numberOfImages];
for (int i = 0; i < numberOfImages; i++)
{
images[i] = new ImageIcon(getClass().getResource("Flower"+Integer.toString(i) + ".png"));
}
}
You say the images are in a folder called "Resources"? You can load images like this then:
BufferedImage image = ImageIO.read(getClass().getResource("/Resources/Flower0.png"));
ImageIcon icon = new ImageIcon(image);
To use it on the GUI you can use a JLabel.
JLabel label = new JLabel();
label.setIcon(icon);
And then add the label to a panel for example.
For me Works...
According to Maven:
https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html
src/main/resources: Application/Library resources
Then I put the ICON in this Location:
PROJECTNAME\src\main\resources\usedPictures\
--Open.png
Clean and Build. And you can check here the location where the file will be get....
PROJECTNAME\target\classes\usedPictures\
--Open.png
Now the Example using the ICON:
button.setIcon(
new javax.swing.ImageIcon(
getClass().getClassLoader().getResource("usedPictures/Open.png")
)
);

Add image to PDF from a URL?

Im trying to add a image from a URL address to my pdf. The code is:
Image image=Image.getInstance("http://www.google.com/intl/en_ALL/images/logos/images_logo_lg.gif");
image.scaleToFit((float)200.0, (float)49.0);
paragraph.add(image);
But it does not work. What can be wrong?
This is a known issue when loading .gif from a remote location with iText.
A fix for this would be to download the .gif with Java (not via the getInstance method of iText's Image class) and to use the downloaded bytes in the getInstance method of the Image class.
Edit:
I went ahead and fixed remote gif loading in iText, it is included from iText 5.4.1 and later.
Adding Image into Itext PDF is not possible through URL .
Only way to add image in PDF is download all images in to local directory and apply below code
String photoPath = Environment.getExternalStorageDirectory() + "/abc.png";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap b = BitmapFactory.decodeFile(photoPath, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap.createScaledBitmap(b, 10, 10, false);
b.compress(Bitmap.CompressFormat.PNG, 30, stream);
Image img = null;
byte[] byteArray = stream.toByteArray();
try {
img = Image.getInstance(byteArray);
} catch (BadElementException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The way you have used to add images to IText PDF is the way that is used for adding local files, not URLs.
For URLs, this way will solve the problem.
String imageUrl = "http://www.google.com/intl/en_ALL/"
+ "images/logos/images_logo_lg.gif";
Image image = Image.getInstance(new URL(imageUrl));
You may then proceed to add this image to some previously open document, using document.add(image).
For further reference, please visit the [Java IText: Image docs].

Categories

Resources