Find the size of selected image from gallery in android - android

I use basic4android and I want to know the size of selected image from gallery.
my code is :
Dim PicChooser As ContentChooser
PicChooser.Initialize("PicChooser")
PicChooser.Show("image/*", "Select a pic")
Sub PicChooser_Result(Success As Boolean, Dir As String, FileName As String)
If Success = True Then
Dim inp As InputStream
inp = File.OpenInput(Dir, FileName)
Dim btm As Bitmap
btm.Initialize2(inp)
end if
end Sub
I use below method in b4a but it doesn't work.
File.Size(Dir,FileName)
it returns zero because Dir and Filename in this sub doesn't really shows the path of the file.

Somewhere i found this maybe untested code:
public static String getContentSizeFromUri(Context context, Uri uri) {
String contentSize = null;
String[] proj = {MediaStore.Images.Media.SIZE };
CursorLoader cursorLoader = new CursorLoader(
context,
uri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null)
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE);
if (cursor.moveToFirst() )
contentSize = cursor.getString(column_index);
}
return contentSize;
}
Check if return value is null before use.

If you already get the Uri of the file, you can use the following code to get some information
if (uri != null) {
File file = new File(uri.getPath());
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("FileName", file.getName());
jsonObject.put("FilePath", file.getAbsolutePath());
jsonObject.put("FileSize", file.length());
} catch (JSONException e) {
e.printStackTrace();
}
}

Related

Picasso 2.5.2 does not load a local image

I am using Picasso 2.5.2 to use it with OkHttp 2.5.0
The code in onCreate() is like below:
File mypath = new File(getFilesDir().getAbsolutePath()+"/"+ date + "image.png");
if (mypath.exists())
{
Picasso.with(FullscreenImage.this).load(mypath).into(fullImage);
Toasty.info(FullscreenImage.this, mypath.toString()).show();
}
else
{
// Download the image from Firebase and create the image in the
// same directory and name
}
I see the image in the files folder in my app folder but it does not display in the image view.
The image size: 1.4 MB
I have resolved my issue by turning the file into a bitmap then use it in the ImageView:
Bitmap bitmap = BitmapFactory.decodeFile(mypath.toString());
fullImage.setImageBitmap(bitmap);
If someone is stuck like me, I did like this, checking on the Picasso webpage (
https://square.github.io/picasso/ ) - section RESOURCE LOADING, line 3:
String drPath = localData[position].getDrawablePath();
if(!drPath.equals(""))
{
var f = **new File(context.getFilesDir(), drPath)**;
try
{
Picasso.get()
.load(f)
.fit()
.centerCrop()
.into(holder.itemImage);
}
}
previously copied the file from Uri to local position like this:
try {
File f = new File(CategoryFragment.this
.getContext()
.getFilesDir()
, fileName);
f.setWritable(true, false);
OutputStream outputStream = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
registered ONLY THE NAME OF THE FILE like this: cmdEditVM.setDrawable(***fileName***, positionForNewDrawable);
It had been retrieved from the Uri with the following (taken from SO):
public String getFileName (Uri uri)
{
String result = null;
if (uri.getScheme().equals("content"))
{
Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
try
{
if (cursor != null && cursor.moveToFirst())
{
int columnIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (columnIndex >= 0) {result = cursor.getString(columnIndex);}
}
}
finally
{
if (cursor != null) {cursor.close();}
}
}
if (result == null)
{
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1)
{
result = result.substring(cut + 1);
}
}
return result;
}

Image path return null in Android

I want to get image path and upload to the server.
Here i successfully read image from gallery and set into image view but image path return null.
public void onActivityResult(int requestCode, int resultCode, Intent data)
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
// Get the url from data
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getRealPathFromURI(getActivity(), selectedImageUri);
Log.i(TAG, "IMAGE" + path);
Log.d("INFO", selectedImageUri.toString());
// Set the image in ImageView
profilepicture.setImageURI(selectedImageUri);
}
}
}
}
/* Get the real path from the URI */
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Delete getRealPathFromURI(), as it is not going to work reliably.
Instead, use your favorite image-loading library (e.g., Picasso, Glide) to load the image from the Uri.
Or, in a worst-case scenario, use getContentResolver().openInputStream() to get an InputStream on the content identified by the Uri, then pass that stream to BitmapFactory.decodeStream(). Just do this I/O on a background thread, please (which image-loading libraries will handle for you, among other benefits).
Update your method getRealPathFromURI:
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String imagePath = cursor.getString(column_index);
if (imagePath == null) {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "New");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File file;
String path = "img_" + timeStamp + ".jpg";
file = new File(mediaStorageDir.getPath() + File.separator + path);
imagePath = file.getAbsolutePath();
ParcelFileDescriptor parcelFileDescriptor = null;
try {
parcelFileDescriptor = context.getContentResolver()
.openFileDescriptor(contentUri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory
.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
saveBitmapToPath(image, imagePath);
} catch (IOException e) {
e.printStackTrace();
}
}
return imagePath;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Use this function to convert String URL to Bitmap
public Bitmap getImage(String url) {
try {
BufferedInputStream bis = new BufferedInputStream(new
URL(url).openStream(), BUFFER_IO_SIZE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos,
BUFFER_IO_SIZE);
copy(bis, bos);
bos.flush();
return BitmapFactory.decodeByteArray(baos.toByteArray(), 0,
baos.size());
} catch (IOException e) {
Log.d(TAG, "loadImageFromArrayList: IMAGE DOWNLOAD FAILED!" +e);
}
return null;
}
try this
String path = yourAndroidURI.toString() // "/mnt/sdcard/FileName.mp3"
File file = new File(new URI(path));

Find image location on HDD, then insert that into SQLite database [duplicate]

I'm trying to upload image to Google Drive from my android app,
based on this tutorial.
When I debug their sample project I see a typical fileUri =
file:///storage/sdcard0/Pictures/IMG_20131117_090231.jpg
In my app I want to upload an existing photo.
I retrieve its path like that
private void GetAnyImage()
{
File dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Pictures/Screenshots");
// --> /storage/sdcard0/Pictures/Screenshots
Log.d("File path ", dir.getPath());
String dirPath=dir.getAbsolutePath();
if(dir.exists() && dir.isDirectory()) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
startActivityForResult(intent,REQUEST_ID);
}
}
and eventually get this typical fileUri =content://media/external/images/media/74275
however when running this line of code
private void saveFileToDrive() {
// progressDialog = ProgressDialog.show(this, "", "Loading...");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
// File's binary content
java.io.File fileContent = new java.io.File(fileUri.getPath());
FileContent mediaContent = new FileContent("image/jpeg", fileContent);
// File's metadata.
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType("image/jpeg");
File file = service.files().insert(body, mediaContent).execute();
I get an error:
java.io.FileNotFoundException: /external/images/media/74275: open failed: ENOENT (No such file or directory)
how can I solve this?
how to convert content://media/external/images/media/Y to file:///storage/sdcard0/Pictures/X.jpg ?
Will something like this work for you? What this does is query the content resolver to find the file path data that is stored for that content entry
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
This will end up giving you an absolute file path that you can construct a file uri from
If you just want the bitmap, This too works
InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();
sample uri : content://media/external/images/media/12345

How to read files at a specific path in android?

I am developing an application in which I open the file explorer and select any file of my choice and retrieve its contents. The default path that opens is /storage/sdcard0 . I am able to read contents of any file that resides directly in this path. However, for any file that in contained in any folder inside /storage/sdcard0/. is inaccessible. The program gives a file not found error. Also, I cannot understand the path that these files have, like for example, if a file resides in path:
/storage/sdcard0/DCIM/100ANDRO/DSC_0001.jpg
,
the logcat shows the path to be:
content:/media/external/images/media/84290/DSC_0001.jpg
How to access this file in my Java code?
Below is the code snippet:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "requestCode received: "+requestCode+" result code: "+resultCode);
if (requestCode == 1 && resultCode == RESULT_OK) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
String folderPath = "Anant";
String filePath = "image.jpg";
String imagePath = saveToInternalStorage(thumbnail, folderPath,
sImageName);
Log.i(TAG, "DeviceAPIS:actual path :: "
+ imagePath.trim().toString());
sendCameraData(imagePath.toString().trim(),
ptrAppContainerForCamera);
}
else if (requestCode == REQUEST_PATH){
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "data.getData() result line 742: " + uri);
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
String base64 ="Error";
byte[] bytesRead = base64.getBytes();
String displayName = null;
String fileName = null;
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = mContext.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
displayName = path + "/" + displayName;
Log.d(TAG, "BEFORE REPLACE: "+displayName);
int index = displayName.indexOf(':');
fileName = displayName.substring(index + 1, displayName.length());
Log.d(TAG,"displayName line 762 " + Part);
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
Log.d(TAG, "FILE BLOCK LINE 768");
displayName = myFile.getName();
Log.d(TAG,"displayName 11" + displayName);
}
try{
File sdcard = Environment.getExternalStorageDirectory();
File readFile = new File(sdcard, fileName);
// File readFile = new File(uri);
int length = (int)readFile.length();
byte[] bytes = new byte[length];
FileInputStream in = new FileInputStream(readFile);
try{
in.read(bytes);
}finally {
in.close();
}
String contents = new String(bytes);
Log.d(TAG,"contents read :: \\n" + contents);
//convert to Base64
bytesRead = contents.getBytes("UTF-8");
base64 = Base64.encodeToString(bytesRead,Base64.DEFAULT);
}catch (Exception e){
Log.d(TAG, "THROWING EXCEPTION");
Log.e(TAG,e.getMessage(),e);
}
}
The exception thrown is java.io.FileNotFoundException. Any help is greatly appreciated.
You can try as below:
String path = null;
Uri originalUri = data.getData();
try {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = this.managedQuery(originalUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index);
} catch (Exception e) {
} finally {
cursor.close();
}
And if path is null, you can get bitmap first and then copy it to your local path.
ContentResolver resolver = this.getContentResolver();
Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri);
.... // copy photo to your local path
you can try this,
1. make sure you have added permission in you manifest file
2. Settings -> Apps -> Your App -> Permissions -> Storage = true/enabled
I had faced a same issue of FileNotFound and i was able to resolve it by #2 above.

Choose text file and Read Android

I chose a text file from storage and got its path (FilePath), am trying to read the content of that text file and put it in edittext..i am using the code below to get text file data and put it in edittext (eTPronounce)
File sdcard = Environment.getExternalStorageDirectory();
//Get the text filea
File file = new File(sdcard,FilePath);
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its i
//Set the text
eTPronounce.setText(text);
}
});
If i replace FilePath (in the second line) with any directory where there is text file it works.For example if I replace FilePath with "Download/text.txt" it works .
I used this link to get FilePath
THANKS
I think you should be using below constructor
File(File dir, String name)
or you can use
File(String path)
If you are specifying directory name then you only need to give the file name as shown in the first example.Otherwise you can use the second one with the complete file path
if(resultCode==RESULT_OK){
if(data == null || data.getData == null){
//Log.e()
return;
}
FilePath = getPath(data.getData(),mActivity);
setfilename.setText(FilePath);
}
public static String getPath(Uri uri,Context ctx) {
String res = null;
if(null==uri){
return res;
}
if (uri != null && uri.toString().startsWith("file://")) {
return uri.toString().substring("file://".length());
}
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = ctx.getContentResolver().query(uri, proj, null, null, null);
if(cursor!=null){
if(cursor.moveToFirst()){
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}catch (Exception ignored){
}finally {
closeCursor(cursor);
}
}
}
closeCursor(cursor);
return res;
}

Categories

Resources