Hello guys i have the problem that i want to include an image in my project and when the user click the print button the image will be printet followed by other information but i dont get it to pass the image path to the PrintTool
PrintTool.printPhotoWithPath(imagePath, this);
and the first line in printtool are this
public static void printPhotoWithPath(String filePath, Context context) {
// Get the picture based on the path
File mfile = new File(filePath/*path*/);
if (mfile.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(filePath/*path*/);
byte[] command = decodeBitmap(bmp);
printPhoto(command, context);
}else{
Log.e("PrintTools_58mm", "the file isn't exists");
}
}
So my problem is, how can i get the path from my image in drawable folder to the code?
Please remove this line
File mfile = new File(filePath/*path*/);
Provided the image is currently in your drawable directory, you can get it like this:
if (mfile.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(getResources(), R.drawable.<yourDrawableName>);
byte[] command = decodeBitmap(bmp);
printPhoto(command, context);
}else{
Log.e("PrintTools_58mm", "the file isn't exists");
}
NB Replace with the name of your Drawable.
If you require the path of the Bitmap, by default it is
String imageUri = "drawable://" + R.drawable.image;
Refer to this.
i hope this helps you
File file = new File(String.valueOf(R.mipmap.imgeName));
file.getPath();
Related
I know that is easy to take a photo and save it to Gallery.
protected async Task<MediaFile> TakePhoto()
{
var storageOptions = new StoreCameraMediaOptions()
{
SaveToAlbum = true,
Directory = pictureAlbumName,
Name = $"test_{DateTime.Now.ToString("HH_mm_ss_ff")}.jpg"
};
return await CrossMedia.Current.TakePhotoAsync(storageOptions);
}
As the result I got the URL that looks like this:
/storage/emulated/0/Android/data/com.companyname.appname/files/Pictures/MyAlbum/photo_18_47_29_69.jpg
But when I tried to save the image from bytes it appears in the folder but never appears in the gallery. After saving the image I tried of course to scan the newly created path but there was no effect
First attempt
File.WriteAllBytes("/storage/emulated/0/Android/data/com.companyname.appname/files/Pictures/MyAlbum/downloaded_image_223213a3as.jpg", immageBytes);
MediaScannerConnection.ScanFile(Application.Context, new string[] { path },null,null);
Second attempt using obsoleted Android methods
Java.IO.File storagePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
string path = System.IO.Path.Combine(storagePath.ToString(), filename);
System.IO.File.WriteAllBytes(path, imageByte);
var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(path)));
CurrentContext.SendBroadcast(mediaScanIntent);
Update:
Basically you need to use this method and save it
private void SaveImageToStorage(Bitmap bitmap)
{
Stream imageOutStream;
if (Build.VERSION.SdkInt >= BuildVersionCodes.Q)
{
ContentValues values = new ContentValues();
values.Put(MediaStore.IMediaColumns.DisplayName,
"image_screenshot.jpg");
values.Put(MediaStore.IMediaColumns.MimeType, "image/jpeg");
values.Put(MediaStore.IMediaColumns.RelativePath,
Android.OS.Environment.DirectoryPictures + Java.IO.File.PathSeparator + "AppName");
Android.Net.Uri uri = this.ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, values);
imageOutStream = ContentResolver.OpenOutputStream(uri);
}
else
{
String imagesDir =Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).ToString() + "/AppName";
imageOutStream = File.OpenRead(System.IO.Path.Combine(imagesDir, "image_screenshot.jpg"));
}
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, imageOutStream);
imageOutStream.Close();
}
OG Answer:
As far as I know, Only images in your media store provider are visible to your gallery and to add it to the media store you need to use the following:
MediaStore.Images.Media.InsertImage(Activity.ContentResolver, ImgBitmap, yourTitle , yourDescription);
Hope this helps :)
I am using Android 7.0 mobile device for my testing.
I am implementing an android app.
I need to take a photo from device camera and just select it from camera folder/ Gallery using by the application.
But after taking a photo and go back to my application and try to select that captured photo by my app, when moving to camera folder, the recently taken photo is not in the gallery.
But I noticed when I take another photo and go to select that photo from again via my app, from the camera folder, I can see the photo I took previously but not the recently taken.
I followed this answer - Android: Refreshing the Gallery after saving new images. But it does not work for me.
If somebody can reply with the answer and that answer contains with a file path to find, please add those details also. ex:- "how to take android camera image gallery path"
The code I use here:-
val cursor: Cursor? = contentResolver.query(uri, projectionColumns, null, null, sortOrder)
if (cursor != null && cursor.moveToFirst()) {
while (cursor.moveToNext()) {
// Get values per item
val imageId = cursor.getString(cursor.getColumnIndex(projectionColumns[0]))
val imageName = cursor.getString(cursor.getColumnIndex(projectionColumns[1]))
val imagePath = cursor.getString(cursor.getColumnIndex(projectionColumns[2]))
val dateTaken = cursor.getString(cursor.getColumnIndex(projectionColumns[3]))
val imageSize = cursor.getString(cursor.getColumnIndex(projectionColumns[4]))
val bucketId = cursor.getString(cursor.getColumnIndex(projectionColumns[5]))
val bucketName = cursor.getString(cursor.getColumnIndex(projectionColumns[6]))
please note that if you are giving the intent a Uri or location somewhere in external or internal private directory to store the image picture after it gets clicked then you need to broadcast it manually or try to move it to another folder.
here is code to broadcast it by passing the path of the file.
public void broadCastMedia(Context context, String path) {
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File file = new File(path);
intent.setData(Uri.fromFile(file));
context.sendBroadcast(intent);
}
and here is how to copy one to another location say pictures directory then you need to create a temp file to pictures directory and an original file and pass to this.
//temp file
File destFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "image.jpg");
//original file
File sourceFile = new File(uri.getPath());
public static Boolean copyFile(File sourceFile, File destFile)
throws IOException {
if (!destFile.exists()) {
destFile.createNewFile();
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null)
source.close();
if (destination != null)
destination.close();
}
return true;
}
return false;
}
and if you have given EXTRA_OUTPUT in intent then you need to store the Uri you have passed as extra as data intent in onActivityResult() will be null at that time you can use the stored Uri to perform any operation on the stored file.
I want to make a feature like default camera feature did. There are a left thumbnail image which show last taken image. When click to the photo, it show the photo and I can slide to view next photo.
My photos is put on "Abc/Pictures" folder.
To get the latest modified file in folder for specific extension
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.filefilter.WildcardFileFilter;
...
/* Get the newest file for a specific extension */
public File getTheNewestFile(String filePath, String ext) {
File theNewestFile = null;
File dir = new File(filePath);
FileFilter fileFilter = new WildcardFileFilter("*." + ext);
File[] files = dir.listFiles(fileFilter);
if (files.length > 0) {
/** The newest file comes first **/
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
theNewestFile = files[0];
}
return theNewestFile;
}
Addition
To get all files or only png and jpeg use
new WildcardFileFilter("*.*");
new WildcardFileFilter(new String[]{"*.png", "*.jpg"});
Use below code find latest images from folder and I hope you are saving images with there time stamp which is standard appraoch.
File path = new File(Environment.getExternalStorageDirectory()
.getPath() + "/Abc/Pictures");
int imagesCount= path .listFiles().length; // get the list of images from folder
Bitmap bmp = BitmapFactory.decodeFile(sdcardPath.listFiles()[imagesCount - 1].getAbsolutePath());
eachImageView.setImageBitmap(bmp); // set bitmap in imageview
I am reading files from the selected folder on my phone like you can see in the following code.
And how could I get this work with an Imagefile?
At the end I like to have an imagelist with a preview of every image.
Like that:
[IMG] (imgview) - [Filename] (String)
for(int i=0; i < files.length; i++) {
File file = files[i];
map = new HashMap<String, String>();
if(!file.isHidden() && file.canRead()) {
path.add(file.getPath());
if(file.isDirectory()) {
map.put("img_list", ""+R.drawable.folder);
map.put("string_cell", file.getName()+"/");
your_array_list.add(map);
}else{
ImageFileFilter filefilter = new ImageFileFilter(file);
if(filefilter.accept(file)){
//Its an imagefile
// ==> I like to replace the ""+R.drawable.image with the file that I have read
map.put("img_list", ""+R.drawable.image);
} else {
//Its not an image file
}
map.put("string_cell", file.getName());
your_array_list.add(map);
}
}
}
SimpleAdapter mSchedule = new SimpleAdapter(this, your_array_list, R.layout.connected_upload_row,
new String[] {"img_list", "string_cell"}, new int[] {R.id.img_list, R.id.string_cell});
list.setAdapter(mSchedule);
In the following picture I like to replace the white "image" picture with the original picture called "41786486733.jpg" as preview.
So that the user can see what picture this is...
EDIT FLORIAN PILZ
if(filefilter.accept(file)){
Log.v("PATH1", file.getPath() );
ImageView myImageView = (ImageView) findViewById(R.id.img_list);
Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath());
myImageView.setImageBitmap(bmp);
}
Looking at the picture, and assuming that the white image with the text "IMAGE" is an ImageView instance, then simply...
Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath);
myImageView.setImageBitmap(bmp);
Or did I completely misunderstood your question.
Anyhow this small example tries to do something similar, what your are trying to accomplish.
There is a similar question with an answer accepted. Check: Cannot open image file stored in sdcard
Snippet from there:
File directory = new File(extStorageDirectory, "myFolder");
File fileInDirectory = new File(directory, files[which]);
Bitmap bitmap = BitmapFactory.decodeFile(fileInDirectory.getAbsolutePath());
You have to implement custom listview check this example and seem storing path in hashmap creating issue,it will more helpful if you provide error log cat! anyhow can you try below trick to achieve you goal instead storing path in hashmap?,hope it will help to you.
File file = new File(Environment.getExternalStoragePath()+"/Folder/");
file imageList[] = file.listFiles();
for(int i=0;i<imageList.length;i++)
{
Log.e("Image: "+i+": path", imageList[i].getAbsolutePath());
Bitmap bitmap = BitmapFactory.decodeFile(imageList[i].getAbsolutePath());
myImageView.setImageBitmap(bitmap);
the solution for my problem is here:
How to show thumbnail from image path?
I had to create a customlistview (with help from ρяσѕρєя K) THANKS!!
create an custom adapter by extended baseadapter class instead of SimpleAdapter . as i think this will be easy or also you can create more custom UI instead of using inbuild
Is there any way that I can get the image path from drawable folder in android as String. I need this because I implement my own viewflow where I'm showing the images by using their path on sd card, but I want to show a default image when there is no image to show.
Any ideas how to do that?
These all are ways:
String imageUri = "drawable://" + R.drawable.image;
Other ways I tested
Uri path = Uri.parse("android.resource://com.segf4ult.test/" + R.drawable.icon);
Uri otherPath = Uri.parse("android.resource://com.segf4ult.test/drawable/icon");
String path = path.toString();
String path = otherPath .toString();
based on the some of above replies i improvised it a bit
create this method and call it by passing your resource
Reusable Method
public String getURLForResource (int resourceId) {
//use BuildConfig.APPLICATION_ID instead of R.class.getPackage().getName() if both are not same
return Uri.parse("android.resource://"+R.class.getPackage().getName()+"/" +resourceId).toString();
}
Sample call
getURLForResource(R.drawable.personIcon)
complete example of loading image
String imageUrl = getURLForResource(R.drawable.personIcon);
// Load image
Glide.with(patientProfileImageView.getContext())
.load(imageUrl)
.into(patientProfileImageView);
you can move the function getURLForResource to a Util file and make it static so it can be reused
If you are planning to get the image from its path, it's better to use Assets instead of trying to figure out the path of the drawable folder.
InputStream stream = getAssets().open("image.png");
Drawable d = Drawable.createFromStream(stream, null);
I think you cannot get it as String but you can get it as int by get resource id:
int resId = this.getResources().getIdentifier("imageNameHere", "drawable", this.getPackageName());
First check whether the file exists in SDCard. If the file doesnot exists in SDcard then you can set image using setImageResource() methodand passing default image from drawable folder
Sample Code
File imageFile = new File(absolutepathOfImage);//absolutepathOfImage is absolute path of image including its name
if(!imageFile.exists()){//file doesnot exist in SDCard
imageview.setImageResource(R.drawable.defaultImage);//set default image from drawable folder
}