Image not saving in folder - android

I am trying to create a folder and save images in it.
But it's not working.
I don't know what's wrong in my code - can you tell me why?
// The method that invoke of uploading images
public void openGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
File folder = new File(this.getExternalFilesDir(
Environment.DIRECTORY_PICTURES), "albumName");
File file = new File(this.getExternalFilesDir(
Environment.DIRECTORY_PICTURES), "fileName"+3);
Bitmap imageToSave = (Bitmap) data.getExtras().get("data");
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Uri selectedImage = data.getData();
Intent i = new Intent(this,
AddImage.class);
i.putExtra("imagePath", selectedImage.toString());
startActivity(i);
}
edit
final File path =
Environment.getExternalStoragePublicDirectory
(
// Environment.DIRECTORY_PICTURES + "/ss/"
//Environment.DIRECTORY_DCIM
Environment.DIRECTORY_DCIM + "/MyFolderName/"
);
// Make sure the Pictures directory exists.
if(!path.exists())
{
path.mkdirs();
}
Bitmap imageToSave = (Bitmap) data.getExtras().get("data");
final File file = new File(path, "file" + ".jpg");
try {
FileOutputStream fos = new FileOutputStream(path);
final BufferedOutputStream bos = new BufferedOutputStream(fos, 8192);
FileOutputStream out = new FileOutputStream(path);
//fos = new FileOutputStream(path);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, fos);
// imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}

How I do make the folder in DCIM and create a file there into:
/*
Create a path where we will place our picture in the user's public
pictures directory. Note that you should be careful about what you
place here, since the user often manages these files.
For pictures and other media owned by the application, consider
Context.getExternalMediaDir().
*/
final File path =
Environment.getExternalStoragePublicDirectory
(
//Environment.DIRECTORY_PICTURES
//Environment.DIRECTORY_DCIM
Environment.DIRECTORY_DCIM + "/MyFolderName/"
);
// Make sure the Pictures directory exists.
if(!path.exists())
{
path.mkdirs();
}
final File file = new File(path, fileJPG + ".jpg");
try
{
final FileOutputStream fos = new FileOutputStream(file);
final BufferedOutputStream bos = new BufferedOutputStream(fos, 8192);
//bmp.compress(CompressFormat.JPEG, 100, bos);
bmp.compress(CompressFormat.JPEG, 85, bos);
bos.flush();
bos.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
fileJPG is the file name I'm creating (dynamically, adding a date).
Replace MyFolderName with albumName.
bmp is my Bitmap data (a screenshot, in my case).

i take a long time for this faking error too and finally it's solve just with add this one line code in manifest
android:requestLegacyExternalStorage="true"

Related

File copy from Gallery pick image to Internal Application Picture Directory Android

Getting image Content from Gallery picture
Now, I want to copy this image file(Which is picked from gallery) to my Internal App folder PICTURE directory(/storage/emulated/0/Android/data/MYApppackage/files/Pictures/).
I am creating new File in PICTURE Directory. file is created in internal AppDir / data / Pictures Directory and image with .JPG format but not showing image. Image is not visible. Image file is created with 0KB data.
I think its a file writing related issue or other i dont know.
Intent intent ;
if (Build.VERSION.SDK_INT < 19) {
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
MainActivity.state = "AddBalance";
startActivityForResult(intent, REQUEST_GALLERY);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_GALLERY);
}
OnActivity Result of Gallery PickUp
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_GALLERY:
if (data != null) {
if (data != null) {
Bitmap bitmap=null;
uri1 = data.getData();
// showPhotoDialog(uri1);
try {
// bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri1);
InputStream image_stream = getActivity().getContentResolver().openInputStream(uri1);
bitmap= BitmapFactory.decodeStream(image_stream);
} catch (IOException e) {
e.printStackTrace();
}
Log.e(TAG,"Data URI----"+data.getData());
try {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "PNG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".PNG", // suffix
storageDir // directory
);
// File imageFile= new File(storageDir,imageFileName);
FileOutputStream out;
try {
// out = getActivity().openFileOutput(image.getName(), Context.MODE_PRIVATE);
out = new FileOutputStream(image.getName());
/* ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
out.write(byteArray);*/
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
} catch (Exception e) {e.printStackTrace();}
// copyFile(new File(getRealPathFromURI(uri1)), image);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}`
}
Edit : Infos
getting value of uri1 from pickup gallery image : content://com.android.providers.media.documents/document/image%3A25877
I am Trying to write bitmap to File. Here is my Code. getBitmap from REQUEST_GALLERY and URI works fine . I am making File in Enviroment.PICTURE directory and write via OutPutStream. but Still File : PNG_54342323111.PNG
I also tried with ByteArrayOutputStream which you can see in comments but didnt works. also tried with OpenFileOutput but not working.

How can I save output image from camera directly to file without compression?

After compressing the file and then texting it, it recompresses again and is very choppy
I use Intent to bring up the camera. I get the result and bring up Intent to send as text.
private void takePic() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 2);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 2) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
File file = writebitmaptofilefirst("route_image",photo);
Uri uri = Uri.fromFile(file);
fileToDelete = file;
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra("address", "8001111222");
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
sendIntent.setType("image/jpg");
startActivityForResult(sendIntent,3);
}
else if (requestCode == 3){
if (fileToDelete.exists()) fileToDelete.delete();
}
}
public static File writebitmaptofilefirst(String filename, Bitmap source) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extStorageDirectory + "/temp_images");
if (!mFolder.exists()) {
mFolder.mkdir();
}
OutputStream outStream = null;
File file = new File(mFolder.getAbsolutePath(), filename + ".jpg");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, filename + ".jpg");
Log.e("file exist", "" + file + ",Bitmap= " + filename);
}
try {
outStream = new FileOutputStream(file);
source.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("file", "" + file);
return file;
}
This works great except the resulting image texted is choppy. If I send the same pic that ends up in the Gallery it converts that down and the result is 100 times better at the receiving end. Can I save the Bitmap I get from the camera call directly without compression, the file will be deleted after the sending of the picture. The user actually takes the pic and then hits the send button on the default sms app.
To save an image directly without compressing use AndroidBmpUtil:
new AndroidBmpUtil().save(source, file);
Instead of
source.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
use
source.compress(Bitmap.CompressFormat.PNG, 100, outStream);
JPEG is a lossy format hence the choppy result.

Creating base64 encoded JPG string from image from camera for upload

I am building an Android app that takes photos, then uploads them to a Rails API.
The api expects the base64 encoded raw file bytes, to be stored as a temp file representing the image in JPG format.
However, the API is rejecting the uploaded file with this error message:
<Paperclip::Errors::NotIdentifiedByImageMagickError:
This seems to be due to a failure of encoding on the part of the Android app.
The base64 image bytes that I'm sending up look like this:
Which appears invalid just by looking at it.
The image is created in android by taking a pic with the Camera API and base64 encoding the resulting byteArray:
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
Anyone know what I'm doing wrong here?
On button click for capturing an image from a camera use this
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
((Activity) context).startActivityForResult(intent, Constants.REQUEST_IMAGE_CAPTURE);
and on activityResult of the activity implement the following code:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final ImageView uploadArea = (ImageView) attachmentDialog.findViewById(R.id.uploadArea);
Bitmap bitmap;
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
Matrix matrix = new Matrix();
matrix.postRotate(-90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
rotatedBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] attachmentBytes = byteArrayOutputStream.toByteArray();
String attachmentData = Base64.encodeToString(attachmentBytes, Base64.DEFAULT);
uploadArea.setImageBitmap(rotatedBitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "CTSTemp" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I hope this will help you, and for any farther info, please ask

Caching exisiting files

I have the following code:
file = new File(getRealPathFromURI(uri));
How am I able to store this in the cache with a name so I can then access it later on?
I know there are methods such as File outputDir = context.getCacheDir();
File outputFile = File.createTempFile("prefix", "extension", outputDir);
But I don't understand how I can store this file in the cache with a specific name so then at a further date I can do file = new File(getActivity().getCacheDir(), "storedFileName"); in other activitys.
Any guidance would be great, thanks.
EDIT:
Here is my main activity where I get a pic from the gallery and it is returned as a uri in the onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
Intent i = new Intent(getApplicationContext(),
sliding_menu.class);
File file = new File(selectedImage.getPath());
ObjectOutput out;
try {
String filenameOffer="Image";
out = new ObjectOutputStream(new FileOutputStream(new File
(getCacheDir(),"")+filenameOffer));
out.writeObject(file);
out.close();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
startActivity(i);
}
}
}
As you can see, I am trying to make the Uri of the selected image, then make it into a file.
Then I am trying to store the file in the cache so I can then further retrieve it throughout my application.
Here is the next activity where I am trying to access the file:
try {
String filename="Image";
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(new File(
getActivity().getCacheDir(),"")+filename)));
String res = (String) in.readObject();
Picasso.with(getActivity().getApplication()).load((res))
.into(mImageView);
} catch (Exception e) {
}
But the image isn't loading. What can I change to make this work?
Example with a .png file
Save File:( InputStream = from internet )
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "MyApp/" + fileName );
if (!f.exists())
{
f.getParentFile().mkdirs();
f.createNewFile();
}
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
Read File:
File path = new File(Environment.getExternalStorageDirectory(),"MyApp/" + fileName);
if(path.exists())
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(path.getAbsolutePath(), options);
}
To store your data on cache file you can use,
Suppose response is string which you want to store in cache.
ObjectOutput out;
try {
String filenameOffer="cacheFileSearch.srl";
out = new ObjectOutputStream(new FileOutputStream(new File
(getActivity().getCacheDir(),"")+filenameOffer));
out.writeObject( response );
out.close();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
And for getting data back from cache file,
try {
String filename="cacheFileSearch.srl";
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(new File(
getActivity().getCacheDir(),"")+filename)));
String res = (String) in.readObject();
} catch (Exception e) {
AppConstant.isLoadFirstTime=true;
}
And for deleting file, you can use
String filename="cacheFileSearch.srl";
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(new File(
getActivity().getCacheDir(),"")+filename)));
File dir = getActivity().getCacheDir();
if (dir.isDirectory()) {
if (new File(new File(dir, "")+filename).delete()) {
}
}
in.close();
} catch (Exception e) {
}

Storing image taken from camera

I can take a picture via the following intent
cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
Then in the onActivityResult method I set the image taken to an ImageView and attempt to store the image to the SD card with the following function
private void savePic(Bitmap bmp) {
if(!isSDOK || !isSDWritable)
return;
String name = "TESTA";
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(path,name+".jpg");
path.mkdirs();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 100 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(bitmapdata);
try{
InputStream is = bis;
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read();
os.write(data);
is.close();
os.close();
}catch(Exception e){Log.e("IMAGE CONVERT ERR", e.toString());}
return;
}
When I check the PICTURES folder i see the file but the image is blank and always 12kb in size. Can't I use my above method to save the image from a bitmap file?
Yes as per the CommonsWare comment you can use EXTRA_OUTPUT like this:
private void capturePhoto() {
File root = new File(Environment.getExternalStorageDirectory(), "Folder");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, "filename.jpeg");
Uri outputFileUri = Uri.fromFile(file);
Intent photoPickerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
photoPickerIntent.putExtra("return-data", true);
startActivityForResult(photoPickerIntent, TAKE_PICTURE);
}

Categories

Resources