Java application saves image on project folder instead of eclipse folder - java

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"

Related

ImageIO.write() not saving file

The absolute file path seems to be forming correctly but the file is not being written.
Code:
var image = ImageIO.read(new ByteArrayInputStream(attachPageScreenshot()));
var saveDirectory = Paths.get("target", "screenshots").toAbsolutePath().toString();
var builder = new StringBuilder();
builder.append("\\").append(context.getDisplayName()).append(".png");
var filePath = saveDirectory.concat(builder.toString());
var saveFile = new File(filePath);
ImageIO.write(image, "png", saveFile);
Output:
java.io.FileNotFoundException: E:\workspace\java\selenium-junit5-starter\target\screenshots\Verify Total Interest Per Annum - Deposit = 30000, Term = 2 Years.png (The system cannot find the path specified)
Anything amiss?
I assumed Paths.get() automatically created the directory if it did not exist.
var dir = new File(saveDirectory);
if (!dir.exists()) {
dir.mkdirs();
}
ImageIO.write(image, "png", saveFile);

how to retriev image from project dir to jlabel?

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.

Saving images in app Folder?

I am making a chat application in which user also has the option to send pictures. I want to save the images to the application folder so I can access those images to fill the chat window up with previous messages with pictures and text. So my question is how can I add an image to the application folder?
Thanks
first you have to create your app name folder into sd card then you have to write your file/image into it
String SDCardRoot = Environment.getExternalStorageDirectory().toString();
String filename = "fileName" + ".jpg";
File myDir = new File(SDCardRoot + "/AppName");
myDir.mkdirs();
File file = new File(myDir, filename);
FileOutputStream fileOutput = new FileOutputStream(file);
//write the file into the sdcard folder specify your buffer , bufferLength
fileOutput.write(buffer, 0, bufferLength);
fileOutput.close();
then only you can access the files from app folder
File imgFile;
String path = Environment.getExternalStorageDirectory() + "/AppName/" + ".jpg";
imgFile = new File(path);
if (imgFile.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(bitmap);
}

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.

droidtext adding image doesn't work

I am desperately trying to insert an image into an existing pdf with droidtext.
The original version of this project was made with iText.
So the code already exists and was modified to fit for Android.
What I do is I take an existing PDF as background.
Insert text and crosses at specified positions within this pdf.
Like filling out a form.
This works quite well so far without changing the code drastically.
Now I want to set an image to the bottom of the page to sign the form.
I used my original code and adapted it a little.
Which doesn't work at all.
I tried to set the image at a specific position. Maybe that was the error.
So i tried to do it the "official" way.
The Pengiuns.jpg image is located on the sd-card.
try {
Document document = new Document();
File f=new File(Environment.getExternalStorageDirectory(), "SimpleImages.pdf");
PdfWriter.getInstance(document,new FileOutputStream(f));
document.open();
document.add(new Paragraph("Simple Image"));
String path = Environment.getExternalStorageDirectory()+"/Penguins.jpg";
if (new File(path).exists()) {
System.out.println("filesize: " + path + " = " + new File(path).length());
}
Image image =Image.getInstance(path);
document.add(image);
document.close();
} catch (Exception ex) {
System.out.println("narf");
}
But still no image at all.
What I get is an PDF with the words "Simple Image" on it and nothing else.
I can access the picture. I get the correct filesize by the if().
No exceptions are thrown.
So my questions are, how do I get an Image located on the SD-Card into my pdf?
What is the mistake here?
But most importantly how do I set the image to a specific location with size within the pdf?
In my original code i use setAbsolutePosition( x, y ) for that.
Eclipse is not complaining when I use it in the code but is it really working?
The reason why you are getting the "Simple Image" is because you have it in Paragraph. In order to add an image, use:
Image myImg1 = Image.getInstance(stream1.toByteArray());
If you want to have it as a footer in the last page you can use the following code but it works with text. You can try to manipulate it for image:
Phrase footerText = new Phrase("THIS REPORT HAS BEEN GENERATED USING INSPECTIONREPORT APP");
HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
doc.setFooter(pdfFooter);
Here is sample code. Here I have uploaded an image to Imageview and then added to pdf. Hope this helps.
private String NameOfFolder = "/InspectionReport";
Document doc = new Document();
try { //Path to look for App folder
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + NameOfFolder;
String CurrentDateAndTime= getCurrentDateAndTime();
// If App folder is not there then create one
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
//Creating new file and naming it
int i = 1;
File file = new File(dir, "Inspection"+Integer.toString(i)+"-" + CurrentDateAndTime+".pdf");
while(file.exists()) {
file = new File(dir, "Inspection"+Integer.toString(i++)+"-" + CurrentDateAndTime+".pdf");}
String filep= file.toString();
FileOutputStream fOut = new FileOutputStream(file);
Log.d("PDFCreator", "PDF Path: " + path);
PdfWriter.getInstance(doc, fOut);
Toast.makeText(getApplicationContext(),filep , Toast.LENGTH_LONG).show();
//open the document
doc.open();
ImageView img1 = (ImageView)findViewById(R.id.img1);
ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
Bitmap bitmap1 = ((BitmapDrawable)img1.getDrawable()).getBitmap();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100 , stream1);
Image myImg1 = Image.getInstance(stream1.toByteArray());
myImg1.setAlignment(Image.MIDDLE);
doc.add(myImg1);
Try following code:
/* Inserting Image in PDF */
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.android);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
//add image to document
doc.add(myImg);

Categories

Resources