Problem saving image in external storage on android - java

I am writing a camera application for the android platform. I am using the CameraKitView Library for producing my camera view. Everything else including accessing the camera is working as expected except for actually capturing and saving the image. minimum sdk is 15 and target sdk and compile sdk is 28. The code for saving the image is as shown below
cameraKitView.captureImage(new CameraKitView.ImageCallback() {
#Override
public void onImage(CameraKitView cameraKitView, byte[] photo) {
File savedPhoto = new File(Environment.getExternalStorageDirectory(), "pchk.jpg");
try{
FileOutputStream outputStream = new FileOutputStream(savedPhoto.getPath());
outputStream.write(photo);
outputStream.close();
}catch (java.io.IOException e){
e.printStackTrace();
}
}
});
Thank you in advance for your assistance

First of all verify that your file or folder where you want to save a file is exists or not, if not create them
capturedFolderPath is a path of the folder where you want to create the file
File folderFile = new File(capturedFolderPath)
if (!folderFile.exists()) {
folderFile.mkdirs();
}
String imageNameToSave = "xyz.jpg";
String imagePath = capturedFolderPath
+ File.separator + imageNameToSave + ".jpg";
File photoFile = new File(imagePath);
if (!photoFile.exists()) {
photoFile.createNewFile();
}
after creating write the bytes on the file like this
FileOutputStream outputStream = new FileOutputStream(photoFile);
outputStream.write(bytes);
outputStream.close();

Related

How to save a bitmap on storage in Android Q and later?

In my application, I have to store a bitmap as a PNG file in shared memory, to make it visible for Gallery app. First, I tried to store the image in /Android/data/package.name/files/Pictures. I got this path from context.getExternalFilesDir(Environment.DIRECTORY_PICTURES). Images stored in this directory are not detected by Gallery. Then I read a few articles and SO posts about MediaStore and I tried to save my image with it.
This is a function that I use to store bitmap. It does not throw any exception, returns true, bitmap.compress() also returns true but I can't find any PNG image in device's memory. I tried to look for it using Gallery and file manager. I also tried to change it to save JPEG instead of PNG but it also does not work.
Could you help me to figure out why this function does not save image to device's store?
I tested it on Samsung A52s 5G, Android 12, OneUI 4.0.
private boolean saveImageToStorageAndroidQ(Bitmap bitmap, String filename) {
filename = filename + ".png";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, filename);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
final ContentResolver resolver = getActivity().getContentResolver();
final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Uri uri = resolver.insert(contentUri, values);
try {
OutputStream imageOutStream = resolver.openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.PNG, 95, imageOutStream);
imageOutStream.flush();
imageOutStream.close();
return true;
} catch (Exception e) {
return false;
} finally {
if (uri != null)
resolver.delete(uri, null, null);
}
}
You can also use this method. Thought it's long, it's better as the other one has been deprecated. Use this code:
String filename = "name.png";
File sd = Environment.getExternalStorageDirectory();
File dest = new File(sd, filename);
try {
FileOutputStream out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
You can use a very easy method:
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, filename, "Description");
This is deprecated. Try this answer

File Couldn't Save On All real device Android Studio

//Save PDF file
//Create time stamp
Date date = new Date() ;
#SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("_yyyy_MM_dd_HH_mm_ss").format(date);
String filePath = Environment.getExternalStorageDirectory() +"/"+ "Allotment" +timeStamp+ ".pdf";
File myFile = new File(filePath);
try {
OutputStream output = new FileOutputStream(myFile);
pdfDocument.writeTo(output);
output.flush();
output.close();
Toast.makeText(AllotmentDoc.this, "PDF Created Succesfully", Toast.LENGTH_LONG).show();
Toast.makeText(AllotmentDoc.this, "PDF Saved On Memory", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
I want to save my pdf file that's why I wrote some line of code. But it works on some device and doesnt work on some other device. What is the problem. how can i solve it.
I think you are facing this problem in some deviece because of
Environment.getExternalStorageDirectory()
You can use
Environment.getExternalStorageDirectory().getAbsolutePath();
Have in mind though, that getExternalStorageDirectory() is not going to work properly on some phones e.g. Galaxy Tab 2, Motorola razr maxx, as it has 2 cards /mnt/sdcard and /mnt/sdcard-ext - for internal and external SD cards respectfully. You will be getting the /mnt/sdcard only reply every time.

Why Isn't My FileOutputstream Writing to a File?

I'm a beginner working on an Android app that uses the gcacace SignaturePad library to capture the signature of my user. My goal is to take the signature, compress it down into a JPEG, and then write that information to a file on the users phone so the picture can be accessed later.
I am currently getting no errors or crashes when I run the code, yet no directory or file is being created when I test the app out on my device(Google Pixel 2). Can anyone give me a hand figuring out where the problem is? I've thrown my head against a wall this entire morning and still don't know.
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("images", Context.MODE_PRIVATE);
if (!directory.exists()) {
directory.mkdirs();
}
File myPath = new File(directory, "1.jpg");
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(myPath);
} catch (Exception e) {
e.printStackTrace();
}
signaturePad.getSignatureBitmap().compress(Bitmap.CompressFormat.JPEG, 90, fOut);
Bitmap signature = signaturePad.getSignatureBitmap();
int bytes = signature.getByteCount();
try {
fOut.write(bytes);
fOut.flush();
fOut.close();
} catch (IOException ex) {
ex.printStackTrace();
}
Toast.makeText(activity_signature_pad.this, "Signature Saved", Toast.LENGTH_SHORT).show();
The code in your question writes to what the Android SDK refers to internal storage. That is private to your app; ordinary users do not have access to it (including you, except when using developer tools).
You appear to want to write to external storage. For that, use:
File directory = new File(getExternalFilesDir(null), "images")

How can I save a screenshots programmatically with out over writing the previously taken screenshot?

I'm working on an android application and I want to save a screenshot of the application. I can save a single screenshot but it keeps over writing the previous screenshot.
I followed a tutorial and modified it but it does not take more than a single screenshot
Attached here is the code in the button action
case R.id.btn_save:
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Bitmap bitmap = getScreenShot(rootView);
int i = 0;
File file = new File("ScreenShot"+ i +".PNG");
if(!file.exists()){
store(bitmap, "ScreenShot"+ i +".PNG");
}
else {
store(bitmap, "ScreenShot"+ i++ +".PNG");
}
and the screenshot storing function
public void store(Bitmap bm, String fileName){
String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
File dir = new File(dirPath);
if (!dir.exists()){
dir.mkdirs();
}
File file = new File(dirPath,fileName);
try{
FileOutputStream fos = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100,fos);
fos.flush();
fos.close();
}catch (Exception e){
e.printStackTrace();
Toast.makeText(this, "Error saving File", Toast.LENGTH_SHORT).show();
}
}
You are declaring i variable inside the button save so you will always start with 0 when button is clicked. To use the way you are trying you should declare that variable outside that scope, but it will restart when you kill and reopen the app.
You can use Shared Preferences to save the following number to use (or the last you used) if you want to use that approach. If not you can use simply
"Screenshot" + System.currentTimeInMillis().toString().
You will also have the time when the screenshot was taken (although in millis). If you want you can format it to be like "user readable" 20191110 for example
Because in that code the file name is always the same- i is always 0. To make it work for one use of the app, i should be a member variable and incremented every screenshot. To make it work more generally, you should generate a random name using File.createTempFile()
case R.id.btn_save:
View rootView getWindow().getDecorView().findViewById(android.R.id.content);
Bitmap bitmap = getScreenShot(rootView);
File dir = new File(Environment.getExternalStorageDirectory(), "Screenshots");
if (!dir.exists())
if ( !dir.mkdirs())
{
Toast ( could not create dir...);
return;
}
int i = 0;
while (++i > 0 )
{
String fileName = "ScreenShot"+ i +".png";
File file = new File(dir, fileName);
if(!file.exists())
{
store(bitmap, file);
break;
}
}
break;
Change the parameter of store(Bitmap bm, String fileName) to store(Bitmap bm, File file)
There you can remove all code before the try block.

Save Image into project folder in web application

I have a requirement of saving the image into project folder. Which is a web application.
I am not able to figure out how to find the absolute path of my folder which I want to save the image. When I am trying to create empty folder and get the absolute path of that I am getting eclipse path.
Can anyone please help me in resolving the issue?
Here is some code I am trying to save the image:
public void saveCustomsLabel(byte[] array, Obj1, String str) throws userException {
byte[] array2 = null;
try {
imageInByte = array;
OutputStream bos = new ByteArrayOutputStream();
InputStream bis = new ByteArrayInputStream(imageInByte);
BufferedImage bImageFromConvert = ImageIO.read(bis);
File path = new File("Templates/Images/Image.bmp")
ImageIO.write(bImageFromConvert, "bmp", path);
May be you should try deploying your project . On local machine the file goes to eclipse path.
use the file location as "/Templates/Images/Image.bmp", this location should be in the same drive on which server is running ( in case of windows ). on linux it will be from root dir.
File path = new File("/Templates/Images/Image.bmp")
This link might help you
Try like this
File file = new File("/opt/image.png");
if(!file.exists()) {
try {
file.mkdirs();
file.createNewFile();
BufferedImage image = new BufferedImage(100,100,1);
ImageIO.write(image, "JPG", file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Categories

Resources