hi i have a problem with a bitmap and a picture located here:
file:///mnt/sdcard/Android/data/com.dev.app/files/Pictures/20120924-092226.jpg
so i have a string with this url (the the file exists!)
now i need to get a bitmap, so i do:
String str = "file:///mnt/sdcard/Android/data/com.dev.app/files/Pictures/20120924-092226.jpg";
Bitmap b = BitmapFactory.decodeFile(str);
but b is always null. and i dont know why.
EDIT: i create the file before with a code like this:
String filename = DateFormat.format("yyyyMMdd-hhmmss",Calendar.getInstance().getTime()) + ".jpg";
Uri imageUri = helper.createImageDestinationUri(null, filename);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, requestCode);
There are two possibilities
The file is of incorrect format, i.e although the extension is .jpg its not a jpeg file.
The file cannot be loaded.
You may have a closer look at the adb logs to see what is going on ... if it does not helps , try the following.
Add the file in your drawable folder, and use it in some Test screen. If the file gets displayed then the file format is correct , so android is not able to load the file. Check your permissions, and actually try and read the file first using FileInputStream or somthing else.
If the file is still not displayed then you can be sure that the format is wrong. In that case just try using a different image file.
Hope it helps...
Related
I'm very new to Android. I'm working with Xamarin and I have to take a picture with camera and save the picture.
I achieved to take the picture, I have a Bitmap object. Then I save it without error but when I try to find it, there is no file.
There is my code :
Bitmap imgBmp = /* image initialized */
//Save image on folder
var folderPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var filePath = System.IO.Path.Combine(folderPath, "image1.png");
var stream = new System.IO.FileStream(filePath, FileMode.Create);
bool isOK = imgBmp.Compress(Bitmap.CompressFormat.Jpeg, 95, stream);
stream.Flush();
stream.Close();
I have no error when execute, isOK is true but when I search for the image.png I'm unable to find the file.
With debugger I saw that the path is : /data/user/0/com.myCompagny.MyAppli/files/image1.png but I can not see that folder.
Can someone help me to find my image1.png ?
Or to change the default folder to something like Pictures\MyApplication\image.png but I don't know how to find default folder for images.
Your file is there, but you have no permissions to see it. App directories are only readable to the owning app's uid. If you try to find your file through the shell, your uid is different.
You should try to use another folder path if you want to save file in a world readable location.
I'm just guessing but maybe System.Environment.SpecialFolder.CommonPictures would do.
I am having a problem with selecting image file from external storage using file picker in Android. This question is the consequence of this question - No such file or diectory error in image file upload using Retrofit in Android. What my problem is opening and reading file from external storage on activity result. I want to convert result URI into File.
I read a pdf file from download folder on activity result
Uri bookUri = data.getData();
if(bookUri!=null)
{
String filePath = bookUri.toString();//bookUri.toString()
String mime = app.getMimeType(filePath);
if(mime!=null && !mime.isEmpty() && (mime.toLowerCase()=="application/pdf" || mime.toLowerCase()=="application/txt" || mime.toLowerCase()=="application/text"))
{
bookFile = new File(bookUri.getPath());
ivBookFile.setImageResource(R.drawable.book_selected);
}
else{
Toast.makeText(getBaseContext(),"Unable to process file you have chosen.",Toast.LENGTH_SHORT).show();
}
}
As you can see I used new File(bookUri.getPath()); to convert into File. The above code works well. It is working. The problem is now I am trying to open an image file in DCIM/Camera folder on activity result.
This is the code I used
Uri selectedImageUri = data.getData();
if(selectedImageUri!=null)
{
try{
bmpCoverImage = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
imageFile = new File(selectedImageUri.getPath());
if(bmpCoverImage!=null)
{
ivCoverImage.setImageBitmap(bmpCoverImage);
}
}
catch (IOException e)
{
Toast.makeText(getBaseContext(),"An error occurred with the file selected",Toast.LENGTH_SHORT).show();
}
}
As you can see I used new File(selectedImageUri.getPath()); like I did in reading pdf file. This time the code is not working. When I do operation with the file like in previous question, it gives me error.
I used this way also
imageFile = new File(Environment.getExternalStorageDirectory(),selectedImageUri.getPath());
I got the same error. How can I open the image file correctly from external storage? How can I convert the chosen file URI from external storage into File?
I am having a problem with selecting image file from external storage using file picker in Android
If you are referring to the code that you are using in this question, you are not "using file picker". You are using ACTION_GET_CONTENT, which has never been a "file picker", nor will it ever be a "file picker".
I want to convert result URI into File.
Usually, that is not necessary. But, if that is what you want to do:
use ContentResolver and openInputStream() to get an InputStream on the content represented by the Uri
create a FileOutputStream on your desired file
use Java I/O to copy the bytes from the InputStream into the FileOutputStream
The above code works well. It is working.
It works for the small number of devices that you tested, for the specific activities that the user chose to handle the ACTION_GET_CONTENT request. It will not work on most Android devices, and it will not work in most circumstances. The only time that code will work is if the Uri has a file scheme. Most of the time, it will not. Instead, it will have a content scheme, representing content supplied by a ContentProvider.
Please how can I open the image file correctly from external storage?
If you wish to continue using ACTION_GET_CONTENT, please understand that this has nothing to do with external storage specifically. You are not getting a file, on external storage or elsewhere. You are getting a Uri. This is akin to a URL, such as the URL for this Web page. Just as a URL does not necessarily point to a file on your hard drive, a Uri does not necessarily point to a file on the filesystem. Use a ContentResolver and DocumentFile to work with the Uri and the content that it identifies.
If you want to always get files on external storage (and nowhere else), then use an actual file picker library.
I was trying to upload an image in the facebook however, when it is about to be posted the image gets pixelized but when the post has been successful the image if not pixelized and it is the right image. How can I fix image that will be sent to facebook's upload picture?
Bitmap bitmap= BitmapFactory.decodeResource(getResources(), img2[res2]);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/LatestShare.jpg";
OutputStream out = null;
File file=new File(path);
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
path=file.getPath();
Uri bmpUri = Uri.parse("file://"+path);
Intent shareIntent = new Intent();
shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/jpg");
startActivity(Intent.createChooser(shareIntent,"Share with"));
I was trying to upload an image in the facebook however, when it is about to be posted the image gets pixelized but when the post has been successful the image if not pixelized and it is the right image. How can I fix image that will be sent to facebook's upload picture?
The image get pixelized by Facebook when you are posting the image? There is nothing wrong with that, that's how they designed it to work. There is nothing you can do from your end
Just do like this send bitmap directory using intent
Bitmap photo = BitmapFactory.decodeFile(picturePath);
Bitmap imageBitmap= ReSizeBitmap.getResizedBitmap(photo, 300, 300);
And send bitmap object Directly using shareIntent.putParceble(imageBitmap)
It seems like you have a resource ID (of an image file), that you are trying to get the image file from.
resources.getResourceName(ID) takes an ID and returns a string representation of the filename.
Let us use this information. Since, we need have the resource ID and need to get the URI,
Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
context.getResources().getResourcePackageName(resourceID) + '/' +
context.getResources().getResourceTypeName(resourceID) + '/' +
context.getResources().getResourceEntryName(resourceID) );
should give the URI. There might be small corrections needed in places. Please feel free to edit my answer to reflect the same.
No compression required. Yay!
Did that help?
Do not process the image. Right now you are decoding the image, then re-encoding it as a JPEG.
Instead, use openRawResource() on Resources() to get an InputStream on the resource, then copy that content to a FileOutputStream using ordinary Java file I/O. Be sure to flush(), getFD().sync(), and close() the FileOutputStream when you are done.
Then, make sure that the MIME type in the shareIntent matches the actual MIME type of the drawable resource. If your resource is a JPEG, what you have now will be fine.
Also:
Do not use concatenation to create a file path. Use File constructors. This ensures that you handle directory separators properly.
Use Uri.fromFile() to convert a File to a Uri, not string concatenation.
Unless you think that the user wants this image to be alongside the rest of their photos, do not use Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES). Instead, use getExternalCacheDir() (available on Context), so you do not clutter up the user's gallery, etc.
However, in the end, your bitmap quality is only partially controlled by you. The app that you are sending it to is welcome to do whatever it wants with the bitmap, and "whatever it wants" may affect the quality. There is nothing you can do about this, other than file bug reports with the other app's authors.
Another, more complex possibility is for you to implement a streaming ContentProvider, to save you from writing the data to a file on external storage and therefore expecting third-party apps to have READ_EXTERNAL_STORAGE as a permission.
I'm trying to retrieve the file that the user wants to share via, for example, the Photo Gallery App. So, when they tap on the share button, and select my application, I'm retrieving the File's Uri through the method Uri fileUri = (Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM);. This works fine.
Then, I try to get the File whose Uri is the one I have. I do that this way:
File file = new File(fileUri.getPath());
But, afterwards, when I try to open it and read it, I get the java.io.FileNotFoundException ENOENT (No such file or directory). Furthermore, when I execute the file.exists() method, it returns false. So I don't know where the problem is.
Here is the code:
Uri fileUri = (Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM);
File file = new File(fileUri.getPath());
FileInputStream imageInFile = new FileInputStream(file);
What am I doing wrong?
EDIT:
I already have the <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> tag in my manifest.
I must also add that the uri of the file which I retrieve is something like: "/0/1/content:/media/external/images/media/9412/ACTUAL/1989334571". As you can see, the file doesn't have any extension at all, so that might be the problem. Nevertheless, I don't know how to solve it.
EDIT 2:
It seems as it is a problem that started since KitKat...
I have a problem when saving image from web.
I create new folder and save all images to this. The problem is I want this folder order by the last download image on first but When i open gallery, the folder is order by the image date created and the date created in the downloaded image is not the time I download but the first time it created. I've already search on stack over flow and see that java can't modified the date created in image to the time I download it.
Any one has the solution? (Sorry for the bad English)
Thanks you for the comment. I will explain more details.
First, I download image from web to cache directory
HttpURLConnection localHttpURLConnection = (HttpURLConnection) new java.net.URL(urldisplay).openConnection();
localHttpURLConnection.setConnectTimeout(30000);
localHttpURLConnection.setReadTimeout(30000);
localHttpURLConnection.setInstanceFollowRedirects(true);
InputStream in = localHttpURLConnection.getInputStream();
File localFile = Constans.fileCache.getCacheFile(urldisplay);
FileOutputStream fos = new FileOutputStream(localFile);
Utils.CopyStream(in, fos); // simple copy by trunks
fos.close();
Second, I copy downloaded image to external storage
File toFile = new File(Environment.getExternalStorageDirectory() + "/folder", "folder_" + System.currentTimeMillis() + ".png");
FileOutputStream fos = new FileOutputStream(toFile);
Utils.CopyStream(new FileInputStream(fromFile), fos);
fos.close();
// Scan image to display when open with gallery otherwise it couldn't see in gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(toFie);
mediaScanIntent.setData(contentUri);
mContext.sendBroadcast(mediaScanIntent);
Lastly, I see that gallery don't sort my image by the time I downloaded. That is the problem i want to fix.
Not sure I understood, but let's try.
First the issue you mention is more specific to Gallery application than a java code issue.
I assume Gallery use EXIF information to order the picture by date they were taken, not oder they are downloaded/copied. Unfortunatly Gallery does not provide any option to sort picture in other oders.
Maybe you can try to use another explorer that allows you to sort the pictures in another order (maybe ESFileExplore which has more options?)
Ultimate solution: you can try to change EXIF in your pictures using a java EXIF library to modify picture taken date and this should change the order they appear in the Galery (but very ugly solution...). Some random EXIF libraries after 5 seconds of Google:
http://drewnoakes.com/code/exif/
http://www.toanthang.net/modules.php?name=News&new_topic=2&catid=7
Hope this helps
Thierry