Convert drawable picture in Bitmap Android - android

How do I convert in Bitmap a droawable resource that I have in form of String as it follows
android.resource://com.example.myapp/drawable/name_picture

Bitmap bitmap= BitmapFactory.decodeResource(context.getResources(),R.drawable.myphoto);

Try the following(there maybe typos):
String path = "android.resource://com.example.myapp/drawable/name_picture";
String[] splitByPath = path.split("drawable/");
if(splitByPath!=null && splitByPath.length >1){
int varId = getResources().getIdentifier(splitByPath[1], "drawable", getPackageName());
Bitmap bmp = BitmapFactory.decodeResource(getResources(),varId);
}else{
//Improper path
}

Uri uriString = Uri.parse("android.resource://com.example.myapp/drawable/name_picture
");
String lastPathIcon = uriString.getLastPathSegment();
int drawableResource = getApplicationContext().getResources()
.getIdentifier("drawable/" + lastPathIcon, null, getApplicationContext().getPackageName());
largeIcon = BitmapFactory.decodeResource(getResources(), drawableResource);
Here the solution that worked for me.

Related

Get image from drawable by path

I am trying to get image that inside drawable folder by path
so i try this but not working
String path = "android.resource:///" + BuildConfig.APPLICATION_ID + "/drawable/logo_ataturk";
File imgFile = new File(path);
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView imgLogo = findViewById(R.id.imageView_logo);
imgLogo.setImageBitmap(myBitmap);
}
I found this simplest solution
Uri path = Uri.parse("android.resource://" + BuildConfig.APPLICATION_ID + "/drawable/logo_ataturk");
ImageView imgLogo = findViewById(R.id.imageView_logo);
imgLogo.setImageURI(path);
Resources are not files on the device. They are files on your developer machine, nothing more.
You can replace all of this code with:
ImageView imgLogo = findViewById(R.id.imageView_logo);
imgLogo.setImageResource(R.drawable.logo_ataturk);
Drawable drawable = getResources().getDrawable(getResources()
.getIdentifier($name_of_the_image, "drawable", getPackageName()));
or
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.large_icon);
imgLogo.setImageBitmap(myBitmap);

Get image from drawable dynamically

I am working on a barcode reader app and I want to show product image when the barcode read, so I renamed photos with product barcode numbers and put drawables folder. Photo name is for ex 1234567, try to retrieve with barcodeNo. But I got error on barcodeNo. How can i do this ?
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageResource(R.drawable.barcodeNo);
just pass your code in getImage method to findout your image from drawable folder.
iv.setImageResource(getImage(barcodeNo));
public int getImage(String imageName) {
int drawableResourceId = this.getResources().getIdentifier(imageName, "drawable", this.getPackageName());
return drawableResourceId;
}
String uri = "#drawable/myresource"; // where myresource (without the extension) is the file
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
Drawable res = getResources().getDrawable(imageResource);
imageView.setImageDrawable(res);
OR
imageview.setImageResource(imageResource)
#Narendra Sorathiya answer is right. you have write this code for solving the NullPointerException, which you posted on screenshot:
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageResource(getImage(barcodeNo));
.
.
.
.
public int getImage(String imageName) {
int drawableResourceId = this.getResources().getIdentifier(imageName, "drawable", this.getPackageName());
return drawableResourceId;
}

setImageBitmap gets Syntax Errors

I am trying to take a Bitmap and display it in an ImageView.
ImageView iv = new ImageView(this);
Bitmap bMap = BitmapFactory.decodeFile("/res/drawable/" + imageFileName);
iv.setImageBitmap(bMap);
That's my code for it. I create an ImageView and a Bitmap. I want to display my Bitmap in my ImageView. But I always get these two errors on the iv.setImageBitmap(bMap); statment
Syntax error on token "bMap", VariableDeclaratorId expected after this token
Syntax error on token(s), misplaced construct(s)
Does anybody has an idea why this happens and what i have to change?
In OP's pastebin code I've found the following snippet:
String imageFileName =getIntent().getStringExtra("imageFileName");
//String bildquelle = "R.drawable." + imageFileName;
public class ImageChange extends Activity {
ImageView iv = new ImageView(this);
String bildquelle = "R.drawable." + imageFileName;
int id = getResources().getIdentifier(bildquelle, "drawable", getPackageName());
Bitmap bMap = BitmapFactory.decodeResource(getResources(), id);
//Bitmap bMap = BitmapFactory.decodeFile("/res/drawable/" + imageFileName);
iv.setImageBitmap(bMap);
}
There are a couple of problems with this including:
The code is not inside a method body.
The code is a Activity subclass.
The code improperly calls getResources().getIdentifier(...).
Instead of the above code I suggest MERGING the rest of activity with the following:
public class BildAnzeigen extends ActionBarActivity {
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bild_anzeigen);
iv = (ImageView) findViewById(R.id.my_image_view); // replace the id with the one from layout definition
handleIntent(getIntent());
}
private void handleIntent(Intent intent) {
String imageFileName = intent.getStringExtra("imageFileName");
int id = getResources().getIdentifier(imageFileName, "drawable", null);
Bitmap bMap = BitmapFactory.decodeResource(getResources(), id);
iv.setImageBitmap(bMap);
}
}
Note: This will not work if the images are not compiled within your apk. There's no way to add anything to drawables after building. It just doesn't work that way.

get Asset UriString

I look for a solution to replace
Images. Media. EXTERNAL_CONTENT_URI (type String uriString) by my asset
InputStream ims = getAssets().open("a.jpg");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
Bitmap bitmap=drawableToBitmap(d);
Uri imageUri = Uri.parse( Images.Media.EXTERNAL_CONTENT_URI + "/" );
bitmap = ImageLoader.loadFromUri( this, imageUri.toString(), 1024, 1024 );
mImageView.setImageBitmapReset( bitmap,0,true);
thank
You can try this:
File file = new File("path_to_image_file");
Uri imageUri = Uri.fromFile(file);

How to get thumbnail for video in my /sdcard/Android/data/mypackage/files folder?

Query to MediaStore.Video.Media.EXTERNAL_CONTENT_URI returns only video in /sdcard/DCIM/100MEDIA
But I want to get thumbnails for video in my /sdcard/Android/data/mypackage/files folder. Is it possible ?
Here is part of my code:
ContentResolver cr = getContentResolver();
String[] proj = {
BaseColumns._ID
};
Cursor c = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);
if (c.moveToFirst()) {
do
{
int id = c.getInt(0);
Bitmap b = MediaStore.Video.Thumbnails.getThumbnail(cr, id, MediaStore.Video.Thumbnails.MINI_KIND, null);
Log.d("*****My Thumbnail*****", "onCreate bitmap " + b);
ImageView iv = (ImageView) findViewById(R.id.img_thumbnail);
iv.setImageBitmap(b);
}
while( c.moveToNext() );
}
c.close();
If you are on android-8 (Froyo) or above, you can use ThumbnailUtils.createVideoThumbnail:
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path,
MediaStore.Images.Thumbnails.MINI_KIND);
Use Glide it will fetch the thumbnail in async.
Glide.with(context)
.load(videoFilePath) // or URI/path
.into(imgView); //imageview to set thumbnail to
3 ways to get a thumbnail from a video:
The best way is to use Glide. It will do all the work in the background, load the thumbnail right into the ImageView and even can show animation when loading. It can work with Uri, byte[] and many other sources.
As #Ajji mentioned:
Glide.with(context)
.load(videoFilePath) // or URI/path
.into(imgView); //imageview to set thumbnail to
If you just need a bitmap in the most efficient way - use ThumbnailUtils.
In my case, it produced a bitmap with a size of 294 912 bytes (video taken with a camera of Nexus5X - 1280x720) and the quality was the same as in the next approach. After you compress into JPEG with 90 it will generate a jpeg file of ~30Kb.
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path,
MediaStore.Images.Thumbnails.MINI_KIND);
The last approach is to use MediaMetadataRetriever. But in my case, it produced a bitmap with size more than 6 times bigger than you got with ThumbnailUtils (with the same quality). So consider it as a last resort.
MediaMetadataRetriever mMMR = new MediaMetadataRetriever();
mMMR.setDataSource(mContext, mAttachment.getUri());
bmp = mMMR.getFrameAtTime();
P.S.: Don't forget that images in Bitmap, byte[] and real file .jpeg formats can be easily converted in any direction within these types. In case of Uri's you often don't have real path to the source file but you can always get the byte stream from it like this:
InputStream in = mContext.getContentResolver().openInputStream(uri);
and with this input stream you can do whatever you want.
You can just use FFmpegMediaMetadataRetriever and forget the reflection:
/**
*
* #param path
* the path to the Video
* #return a thumbnail of the video or null if retrieving the thumbnail failed.
*/
public static Bitmap getVideoThumbnail(String path) {
Bitmap bitmap = null;
FFmpegMediaMetadataRetriever fmmr = new FFmpegMediaMetadataRetriever();
try {
fmmr.setDataSource(path);
final byte[] data = fmmr.getEmbeddedPicture();
if (data != null) {
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
if (bitmap == null) {
bitmap = fmmr.getFrameAtTime();
}
} catch (Exception e) {
bitmap = null;
} finally {
fmmr.release();
}
return bitmap;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmapThumb = MediaStore.Video.Thumbnails.getThumbnail(mActivity.getContentResolver(),
Long.parseLong(video_id),
Images.Thumbnails.MINI_KIND,
options);
Use Options to load bitmap of decrease the bitmap size..
see #Ajji 's answer :
Glide.with(context)
.load(videoFilePath) // or URI/path
.into(imgView); //imageview to set thumbnail to
It sometimes returns black image, this issue is already mentioned in Glide library's issues
Use this code:
BitmapPool bitmapPool = Glide.get(activity).getBitmapPool();
int microSecond = 6000000;// 6th second as an example
VideoBitmapDecoder videoBitmapDecoder = new VideoBitmapDecoder(microSecond);
FileDescriptorBitmapDecoder fileDescriptorBitmapDecoder = new FileDescriptorBitmapDecoder(videoBitmapDecoder, bitmapPool, DecodeFormat.PREFER_ARGB_8888);
Glide.with(activity)
.load(videoPath)
.asBitmap()
.override(50,50)// Example
.videoDecoder(fileDescriptorBitmapDecoder)
.into(holder.ivFirstUpload);
Get video thumbnail from VIDEO_ID:
public static Drawable getVideoThumbnail(Context context, int videoID) {
try {
String[] projection = {
MediaStore.Video.Thumbnails.DATA,
};
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(
MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
projection,
MediaStore.Video.Thumbnails.VIDEO_ID + "=?",
new String[] { String.valueOf(videoID) },
null);
cursor.moveToFirst();
return Drawable.createFromPath(cursor.getString(0));
} catch (Exception e) {
}
return null;
}
Here is a similar answer to Matthew Willis but with added reflection. Why? because science.
/**
*
* #param path
* the path to the Video
* #return a thumbnail of the video or null if retrieving the thumbnail failed.
*/
public static Bitmap getVidioThumbnail(String path) {
Bitmap bitmap = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
bitmap = ThumbnailUtils.createVideoThumbnail(path, Thumbnails.MICRO_KIND);
if (bitmap != null) {
return bitmap;
}
}
// MediaMetadataRetriever is available on API Level 8 but is hidden until API Level 10
Class<?> clazz = null;
Object instance = null;
try {
clazz = Class.forName("android.media.MediaMetadataRetriever");
instance = clazz.newInstance();
final Method method = clazz.getMethod("setDataSource", String.class);
method.invoke(instance, path);
// The method name changes between API Level 9 and 10.
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD) {
bitmap = (Bitmap) clazz.getMethod("captureFrame").invoke(instance);
} else {
final byte[] data = (byte[]) clazz.getMethod("getEmbeddedPicture").invoke(instance);
if (data != null) {
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
if (bitmap == null) {
bitmap = (Bitmap) clazz.getMethod("getFrameAtTime").invoke(instance);
}
}
} catch (Exception e) {
bitmap = null;
} finally {
try {
if (instance != null) {
clazz.getMethod("release").invoke(instance);
}
} catch (final Exception ignored) {
}
}
return bitmap;
}
If you are directly creating thumbnails as follows
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path,
MediaStore.Images.Thumbnails.MINI_KIND);
Then there is a problem with this method if your are creating thumbnails for large video set(for large number of videos). the application will freeze until all the thumbnails are loaded because all the process are executing in the main thread.
Use SuziLoader
This loader will load the thumbnails for the videos which is locally stored on your filesystem in background.
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/video.mp4";
ImageView mThumbnail = (ImageView) findViewById(R.id.thumbnail);
SuziLoader loader = new SuziLoader(); //Create it for once
loader.with(MainActivity.this) //Context
.load(path) //Video path
.into(mThumbnail) // imageview to load the thumbnail
.type("mini") // mini or micro
.show(); // to show the thumbnail
To get this dependency use the following steps
Step 1. Add the JitPack repository to your build file
Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Step 2. Add the dependency
dependencies {
compile 'com.github.sushinpv:SuziVideoThumbnailLoader:0.1.0'
}
ADD READ EXTERNAL STORAGE Permission in manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Try something similar to this code snippet:
img.setImageBitmap(ThumbnailUtils.createVideoThumbnail(
Environment.getExternalStorageDirectory().getPath() + "/WhatsApp/Media/WhatsApp Video/"+getItem(position),
MediaStore.Video.Thumbnails.FULL_SCREEN_KIND));
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection = { MediaStore.Video.VideoColumns.DATA };
Cursor c = getContentResolver().query(uri, projection, null, null, null);
int vidsCount = 0;
if (c != null) {
vidsCount = c.getCount();
while (c.moveToNext()) {
String path = c.getString(0);
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path,
MediaStore.Images.Thumbnails.MINI_KIND);
}
c.close();
}
You can use this method with any Uri:
public static Bitmap getVideoFrame(Uri uri, Context context) {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(context, uri);
return retriever.getFrameAtTime();
}

Categories

Resources