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);
Related
DETAILS : My application creates a pdf using data previously entered. The PDF is created in the application itself using :
//PDF GENERATOR
implementation 'com.itextpdf:itext7-core:7.1.3'
implementation 'com.itextpdf:itextg:5.5.10'
I view that PDF in the same Activity using :
//PDF VIEW
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
The code for that is as follows :
private void createPdf() throws FileNotFoundException {
File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "Zomato/Receipts");
file = new File(folder.getAbsolutePath(), "Reciept.pdf");
pdfView.fromFile(file).load();
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
OutputStream outputStream = new FileOutputStream(file);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDocument = new PdfDocument(writer);
pdfDocument.setDefaultPageSize(PageSize.A4.rotate());
Document document = new Document(pdfDocument);
document.setMargins(15, 15, 15, 15);
float[] columnWidth = {110, 550, 140};
Table table1 = new Table(columnWidth);
//Table1------- 01
table1.addCell(new Cell().add(new Paragraph("Hello Welcome")).setVerticalAlignment(VerticalAlignment.MIDDLE));
table1.addCell(new Cell().add(new Paragraph("This is the PDF Data").setBold().setFontSize(14f)
.setTextAlignment(TextAlignment.CENTER)));
table1.addCell(new Cell().add(new Paragraph("Address : " + Common.currentCompany.getAddress()).setBold().setFontSize(8f).setTextAlignment(TextAlignment.CENTER)));
document.add(table1);
document.close();
textView.setText(R.string.downloaded_message);
}
This code works on phone Samsung M31 but it does not work on Redmi Y2 and Oppo. When I run this code on these phones I get the following error :
E/PDFView: load pdf error
java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)
Please help. I have been stuck on this problem for a long time.
Thank you for the help. So here is the solution. I replaced this part of the code :
File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "Zomato/Receipts");
file = new File(folder.getAbsolutePath(), "Reciept.pdf");
pdfView.fromFile(file).load();
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
OutputStream outputStream = new FileOutputStream(file);
With this :
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File folder = new File(root.getAbsolutePath() + "/" + DOCUMENTS);
Log.e("Tag", folder.getAbsolutePath());
if (!folder.exists()) {
folder.mkdirs();
}
File file = new File(folder.getAbsolutePath() + "/" + epoch + ".pdf");
And I shifted the PDFView to the bottom below:
document.close();
pdfView.fromFile(file).load();
i want to convert a file path to a uri. but i get errors saying it can't resolve the uri. The image come from saving an image from a camera intent. the image is saved to this directory: getFilesDir(); which is in the app.
in my cursor adapter:
String imgPath = cursor.getString(cursor.getColumnIndexOrThrow( InventoryContract.InventoryEntry.COLUMN_PRODUCT_IMG_PATH ));
String productName = cursor.getString(cursor.getColumnIndexOrThrow( InventoryContract.InventoryEntry.COLUMN_PRODUCT_NAME ));
int productStock = cursor.getInt(cursor.getColumnIndexOrThrow( InventoryContract.InventoryEntry.COLUMN_PRODUCT_STOCK ));
Uri uri = ContentUris.withAppendedId(InventoryContract.InventoryEntry.CONTENT_URI,
cursor.getLong(cursor.getColumnIndexOrThrow( InventoryContract.InventoryEntry.COLUMN_PRODUCT_ID )));
File imgFile = new File(imgPath);
Uri imgURI = Uri.fromFile(imgFile);
if(imgFile.exists()) {
Log.v("image file" , String.valueOf(imgFile));
//Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
productImage.setImageURI(imgURI);
Log.v("Image does exist", "file | " + String.valueOf(imgURI));
}
else {
Log.v("bitmap --- ", "Could not find file | " + imgPath);
}
one of the error lines:
W/ImageView: resolveUri failed on bad bitmap uri: file:///data/user/0/com.example.android.inventoryapp/files/JPEG_20170710_094130_1552703275.jpg
Try to use this below code
Uri uri = Uri.fromFile(new File(filepath));
thanks everyone for the help. I found a solution. The filepath was good but it was an empty file, i think. I had to write to it like this:
private File createImageFile(Bitmap image) throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File directory = this.getFilesDir();
// Save Bitmap
this.photo = new File(directory, imageFileName + ".jpg");
this.photo.createNewFile();
// Write to/Compress the Bitmap from the camera intent to the file
FileOutputStream fos = new FileOutputStream(this.photo);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
// path to file
this.imgPath = this.photo.getAbsolutePath();
return this.photo;
}
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);
}
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"
Is it possible to generate a new image name for each image that is processed using the following code (I have highlighted the relevant section)?
public static void makeBinary(File image) {
try{
//Read in original image.
BufferedImage inputImg = ImageIO.read(image);
//Obtain width and height of image.
double image_width = inputImg.getWidth();
double image_height = inputImg.getHeight();
//New images to draw to.
BufferedImage bimg = null;
BufferedImage img = inputImg;
//Draw the new image.
bimg = new BufferedImage((int)image_width, (int)image_height, BufferedImage.TYPE_BYTE_BINARY);
Graphics2D gg = bimg.createGraphics();
gg.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
// ************* THIS IS WHERE I AM HAVING DIFFICULTY ***************
//Save new binary (output) image.
String temp = "_inverted";
File fi = new File("images\\" + temp + ".jpg");
ImageIO.write(bimg, "jpg", fi);
// ******************************************************************
}
catch (Exception e){
System.out.println(e);
}
}
I have 300 images, numbered 001.jpg - 300.jpg, and what I would like is for each new outputted image to be named something along the lines of, binary_001.jpg - binary_300.jpg.
The method that calls makeBinary() is located in another class and is:
public static void listFiles() {
File dir = new File("images");
File imgList[] = dir.listFiles();
if(dir.isDirectory()){
for(File img : imgList){
if(img.isFile()){
MakeBinary.makeBinary(img);
System.out.println(img + ": processed successfully.");
}
else{
System.out.println("Directory detected; skipping to next file,");
}
}
}
}
How can I go about achieving this?
Many thanks.
Get the filename from your File image parameter and add it to the new filename:
String temp = image.getName() + "_inverted";
File fi = new File("images\\" + temp + ".jpg");
ImageIO.write(bimg, "jpg", fi);
You can just concatenate name from the original image (in your code 'image' you pass to ImageIO with the string "_inverted", this way you would have original name for each image you process: image.jpg -> image_inverted.jpg
File fi = new File("images\\" + "binary_" + image.getName());
Should do the trick.
Or even better:
File fi = new File(image.getParent(), "binary_" + image.getName());