I've got an Image Uri, retrieved using the following:
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
This works just amazing for Intents that require an Image URI, etc (so I know for sure the URI is valid).
But now I want to save this Image URI to a file on the SDCARD. This is more difficult because the URI does not really point at a file on the SDCARD or the app.
Will I have to create a bitmap from the URI first, and then save the Bitmap on the SDCARD or is there a quicker way (preferable one that does not require the conversion to a bitmap first).
(I've had a look at this answer, but it returns file not found - https://stackoverflow.com/a/13133974/1683141)
The problem is that the Uri you've been given by Images.Media.insertImage() isn't to an image file, per se. It is to a database entry in the Gallery. So what you need to do is read the data from that Uri and write it out to a new file in the external storage using this answer https://stackoverflow.com/a/8664605/772095
This doesn't require creating a Bitmap, just duplicating the data linked to the Uri into a new file.
You can get the data using an InputStream using code like:
InputStream in = getContentResolver().openInputStream(imgUri);
Update
This is completely untested code, but you should be able to do something like this:
Uri imgUri = getImageUri(this, bitmap); // I'll assume this is a Context and bitmap is a Bitmap
final int chunkSize = 1024; // We'll read in one kB at a time
byte[] imageData = new byte[chunkSize];
try {
InputStream in = getContentResolver().openInputStream(imgUri);
OutputStream out = new FileOutputStream(file); // I'm assuming you already have the File object for where you're writing to
int bytesRead;
while ((bytesRead = in.read(imageData)) > 0) {
out.write(Arrays.copyOfRange(imageData, 0, Math.max(0, bytesRead)));
}
} catch (Exception ex) {
Log.e("Something went wrong.", ex);
} finally {
in.close();
out.close();
}
Related
I am trying to creating pdfs from images in my Android application.
I get the image successfully and created the pdf file successfully. But When I open my pdf file, images are not displayed. I have tried many solutions on Internet but all in vain.
I am pasting my code. Kindly guide me.
First I am pasting the code for getting image from gallery
Intent myIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(myIntent,120);
Now I am pasting the code of OnActivityResult Method, in which I am getting the image and craeating a pdf file.
try {
Document doc = new Document();
if (resultCode == RESULT_OK) {
if (requestCode == 120) {
if (data.getData() != null) {
Uri uri = data.getData();
Image image = Image.getInstance(uri.toString());
FileOutputStream fileOutputStream =openFileOutput("mypdf.pdf", Context.MODE_PRIVATE);
PdfWriter.getInstance(doc, fileOutputStream);
doc.open();
doc.add(image);
doc.close();
}
}
}
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
As you are using iText you need to create BitMap format of image and then need to add into pdf.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(contentResolver, <pass the uri of image>);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAbsolutePosition(470f,755f);
myImg.scaleToFit(100f,100f);
document.add(myImg);
I have solved it, The solution was to use Input Stream as follows:
Uri uri = data.getData();
InputStream ims = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(ims);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Image image = Image.getInstance(byteArray);
doc.add(image);
doc.close();
This is the code i used to get the uri of my image
Uri imageUri = data.getData();
How do I get the actual path of an image selected?
the Uri value/path that i am currently getting is
content://com.miui.gallery.open/raw/%2Fstorage%2Femulated%2F0%2FLightStick%2F144pixels.bmp
the correct filepath of the image that i need is for my other function is
/storage/emulated/0/LightStick/144pixels.bmp
The image selection function:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK){//everything processed successfully
if(requestCode == IMAGE_GALLERY_REQUEST){ //hearing back from image gallery
//the address of the image on the SD card
Uri imageUri = data.getData();
BMPfilepath =imageUri.getPath();
//stream to read image data from SD card
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(imageUri);//getting an input stream, based no the URI of image
Bitmap image = BitmapFactory.decodeStream(inputStream);//get bitmap from stream
imgPicture.setImageBitmap(image);//show image to user in imageview
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show(); //let user know image unavail
}//catch
} //requestCode == IMAGE_GALLERY_REQUEST
}
The upload function which uses the imageUri from the previous function.
String path = imageUri.getPath().toString(); the app crashes and goes to a looper file when in debug
public void onUploadToArduino(){
String path = imageUri.getPath().toString();//<- app crashes and goes to a looper file when in debug
String sdpath = System.getenv("EXTERNAL_STORAGE");
String extStore = Environment.getExternalStorageDirectory().getPath();
String FILENAME = extStore + "/LightStick/144pixels.bmp";
String collected = null;
FileInputStream fis = null;
FileInputStream fileInputStream = null;
byte[] bytesArray = null;
try {
File file = new File(FILENAME);//<- this works
//File file = new File(path);//<- this doesnt
bytesArray = new byte[(int) file.length()];
//read file into bytes[]
fileInputStream = new FileInputStream(file);
fileInputStream.read(bytesArray);
How do I get the actual path of an image selected?
You don't. A Uri is not a file and may not point to a file, let alone one that you can access.
Use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. Ideally, just use the stream. If you need a File for some other API that is poorly written and does not support streams:
Create a FileOutputStream on some File that you control (e.g., in getCacheDir())
Use the InputStream and the FileOutputStream to copy the bytes to your file
Use your file
I am trying to save a bitmap which user selects into my own App path.
Unfortunately, with very big images I get OutOfMemoryError error.
I am using the following code:
private String loadImage (Uri filePath) {
File fOut = new File(getFilesDir(),"own.jpg");
inStream = getContentResolver().openInputStream(filePath);
selectedImage = BitmapFactory.decodeStream(inStream);
selectedImage.compress(CompressFormat.JPEG, 100, new FileOutputStream(fOut));
}
Is there any way for me to save any image file of any size for an Uri to a file?
*I am not in a position to resize the image e.g. by using calculateInSampleSize method.
Is there any way for me to save any image file of any size for an Uri to a file?
Since it already is an image, just copy the bytes from the InputStream to the OutputStream:
private void copyInputStreamToFile( InputStream in, File file ) {
try {
FileOutputStream out = new FileOutputStream(file);
byte[] buf = new byte[8192];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.flush();
out.getFD().sync();
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
(adapted from this SO answer)
Ok, I tried this code:
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
and looks like it can't do the job. When I log it it prints:
content://media/external/images/media/25756
which doesn't helps me because I need it for new File(Uri). Strangely, getImageUri method returns Uri, but File doesn't seem to recognize it. Anyone has method to retrieve Uri from freshly made bitmap?
P.S. As far as I read, it doesn't work since KitKat.
edit
This code works and from this I want to retrieve Uri:
croppedBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
cropImageView = (CropImageView) findViewById(R.id.CropImageView);
cropImageView.setImageBitmap(croppedBitmap);
Button crop = ...;
crop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cropContainer.setVisibility(View.GONE);
mImageView.setVisibility(View.VISIBLE);
Bitmap croppedImage = cropImageView.getCroppedImage();
mImageView.setImageBitmap(croppedImage);
paramsContener.setVisibility(View.VISIBLE);
}
});
and looks like it can't do the job
That would depend upon what "the job" is.
When I log it it prints: content://media/external/images/media/25756 which doesn't helps me because I need it for new File(Uri)
First, if you want to save a bitmap to a file, use a FileOutputStream rather than a ByteArrayOutputStream. Java file I/O has been around for ~20 years.
Second, if you are expecting to get file paths from a ContentProvider like MediaStore, you are going to be disappointed. You get back a Uri, like the content:// one in your question. A Uri is not a file. Use a ContentResolver and methods like openInputStream() to read in the data identified by that Uri. The concept of a "URI" representing an opaque handle to something you get via a stream has been around at least as long as has HTTP, which has been around for ~25 years.
Strangely, getImageUri method returns Uri, but File doesn't seem to recognize it.
That is because a Uri is not a file.
Okay, I got it thanks to #CommonsWare - made something like this. Hope will help it another people as well:
public String makeBitmapPath(Bitmap bmp){
// TimeStamp
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "Photo"+ timeStamp +".jpg"); // the File to save to
try {
fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close(); // do not forget to close the stream
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
} catch (IOException e){
// whatever
}
return file.getPath();
}
I want to check, if the current user picture of a contact is the same as the one on the sd card...
I set the user picture like following:
byte[] photo = ImageFunctions.convertImageToByteArray(bitmap);
ContentValues values = new ContentValues();
....
values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, photo);
...
And I read the image like following:
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(
contentResolver,
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, mId),
fullsize);
if (inputStream != null)
return BitmapFactory.decodeStream(inputStream);
And my convert function is following:
public static byte[] convertImageToByteArray(Bitmap bitmap)
{
ByteArrayOutputStream streamy = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, streamy);
return streamy.toByteArray();
}
And I use a md5 hash on the byte array of the bitmap to find changes... Actually, the images are not exactly the same.
What can I do, so that I compare the hash codes? It seems, like compression or whatever is not exactly the same, so the md5 hash check fails...