Saving images in app Folder? - java

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);
}

Related

Android - Convert file path to uri (not working)

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;
}

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"

Create a .zip file in Java with images

I'm creating a Java program which gets images from a JFileChooser and create a .zip file containing the selected images. I get the files with this code:
final JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.setFileFilter(new FileNameExtensionFilter("Image files", "bmp", "png", "jpg"));
fc.setAcceptAllFileFilterUsed(false);
fc.showOpenDialog(null);
File files[] = fc.getSelectedFiles();
How i create a .zip file containing the files of the files[] array?
Thank you for your help :D.
File someFile = new File("someFile.zip");
File files[] = fc.getSelectedFiles();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(someFile));
// Create the ZIP file first
try (ZipOutputStream out = new ZipOutputStream(bos)) {
// Write files/copy to archive
for (File file : files) {
// Put a new ZIP entry to output stream for every file
out.putNextEntry(new ZipEntry(file.getName()));
Files.copy(file.toPath(), out);
out.closeEntry();
}
}

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