I am using Universal-Image-Loader and there is this functionality that access the file cache of the image from sd card. But I don't know how to convert the returned file cache into bitmap. Basically I just wanted to assign the bitmap to an ImageView.
File mSaveBit = imageLoader.getDiscCache().get(easyPuzzle);
Log.d("#ImageValue: ", ""+mSaveBit.toString());
mImageView.setImageBitmap(mSaveBit);
Error: "The method setImageBitmap(Bitmap) in the type ImageView is not applicable for the arguments (File)"
You should be able to use BitmapFactory:
File mSaveBit; // Your image file
String filePath = mSaveBit.getPath();
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
mImageView.setImageBitmap(bitmap);
Define File
String fileName = "/myImage.jpg";
File file = new File(fileName);
get Bitmap of Image
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Set Bitmap to ImageView
myImageView.setImageBitmap(bitmap);
You can use this function to get Bitmap from file path
fun getBitmap(filePath:String):Bitmap?{
var bitmap:Bitmap?=null
try{
var f:File = File(path)
var options = BitmapFactory.Options()
options.inPreferredConfig = Bitmap.Config.ARGB_8888
bitmap = BitmapFactory.decodeStream(FileInputStream(f),null,options)
}catch (e:Exception){
}
return bitmap
}
Here is a simple code to create a scaled image for ImageView in this case
- Width:400
- Height:400
final File file = new File(Environment.getExternalStorageDirectory(),"b.jpg");
ImageView img = (ImageView) findViewById(R.id.imageview);
img.setImageBitmap(Bitmap.createScaledBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()),400,400,false));
Kotlin Version
if (requestCode==PICK_IMAGE_REQUEST){
if (data!=null){
selectedfileUri=data.data
if (selectedfileUri!=null && !selectedfileUri!!.path.isEmpty()){
val file = FileUtils.getFile(context,selectedfileUri)
val bitmap = BitmapFactory.decodeFile(file.path)
uimg!!.setImageBitmap(bitmap)
}
}
}
This is not the right question, but if you use flag .cacheInMemory() in ImageLoader setup you can retrive the bitmap without need of recreate at any time using BitmapFactory to safe memory usage .
Just use:
Bitmap bitmap = ImageLoader.getInstance().getMemoryCache()·get("url as key");
Related
I want to add images from asses to an imageview automatically. the below code does work well when images are in a drawable folder, but I want to create a separate folder name avatar in the asset folder and get random images from there in my imageview.
int[] images = new int[] {R.drawable.image01, R.drawable.image02, R.drawable.image03};
// Get the ImageView
setContent(R.layout.main);
ImageView mImageView = (ImageView)findViewById(R.id.myImageView);
// Get a random between 0 and images.length-1
int imageId = (int)(Math.random() * images.length);
// Set the image
mImageView.setBackgroundResource(images[imageId]);
Thanks in advance.
I suggest you to use AssetManager.list()
To list all the assets for the given folder within /assets folder, we use AssetManager.list(). Suppose we have some files within /assets/img and we need to list all those files, then we write code as follows.
String[] imgPath = assetManager.list("img");
Here we get String array of file names within img directory.
try {
String[] imgPath = assetManager.list("img");
for (int i = 0; i< imgPath.length; i++) {
InputStream is = assetManager.open("img/"+imgPath[i]);
Log.d(TAG, imgPath[i]);
Bitmap bitmap = BitmapFactory.decodeStream(is);
imageViewbyCode = new ImageView(this);
imageViewbyCode.setImageBitmap(bitmap);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
imageViewbyCode.setLayoutParams(params);
myLayout.addView(imageViewbyCode);
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
Please try below code:-
AssetManager assetManager = getAssets();
ImageView mImageView = (ImageView)findViewById(R.id.myImageView);
InputStream inputStream = assetManager.open("yourimage.jpg")
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
mImageView.setImageBitmap(bitmap);
I have some problem with my code..
I want to set value luckywheelitem library from https://github.com/thanhniencung/LuckyWheel ,
I have image file from gallery then convert to bitmap
String root = Environment.getExternalStorageDirectory().toString() + "/Luckywheel";
Bitmap bitmap = BitmapFactory.decodeFile(root+ "/sarada.png" );
Then i want set value luckyItem1.icon = ; but just receive integer value
how to convert from image bitmap to int (drawable)
Thank you for attention
You should pass to luckyItem1.icon only a resource file. You should add drawable to your project and then use it.
Example:
luckyItem1.icon = R.drawable.luckyItemIcon
I have the real path of an image which I am retrieving from my Database.
I want to set the ImageView by using the real path (/storage/emulated/0/DCIM/100MEDIA/image.jpg)
How can this be done?
public void getIMG(){
Cursor res = myDb.GetRow(id);
if(res.moveToFirst()){
String path = res.getString(DatabaseHelper.ROWIMG);
/*img.set'???'*/
}
}
hi try this and see if it helps you
String imagePath = cursor.getString(column_index_data);
File file = new File(imagePath);
file.getAbsolutePath();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true ;
BitmapFactory.decodeFile(filePath , options);
options.inSampleSize = scaleFactor ;
options.inJustDecodeBounds = false ;
Bitmap newBitmap = BitmapFactory.decodeFile(filePath , options);
The best answer is to use a library like Picasso, to have it load the image in the background and apply it to your ImageView when the image is ready.
If you are determined to re-invent this wheel yourself, use BitmapFactory.decodeFile() on a background thread to read in the file and give you a Bitmap that you can pass to the ImageView.
I want to get Bitmap from ImageView. I have used following code, but getDrawable() returns null. How to get whole Bitmap from ImageView.
Bitmap bitmap;
if (mImageViewer.getDrawable() instanceof BitmapDrawable) {
bitmap = ((BitmapDrawable) mImageViewer.getDrawable()).getBitmap();
} else {
Drawable d = mImageViewer.getDrawable();
bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
d.draw(canvas);
}
storeImage(bitmap,"final.jpeg");
If you just want the Bitmap from a ImageView the following code may work for you:-
Bitmap bm=((BitmapDrawable)imageView.getDrawable()).getBitmap();
Try having the image in all drawable qualities folders (drawable-hdpi/drawable-ldpi etc.)
Could be that the emulator or device your using has a different density and is trying to pull images from another folder.
If you are using an extension in your image other than .png, .jpg, or .gif, It might not recognize other extension types. http://developer.android.com/guide/topics/resources/drawable-resource.html
According to this answer, just do it like this:
imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
For Kotlin:
simply write this code to get the bitmap from an ImageView
imageview.invalidate()
val drawable = imageview.drawable
val bitmap = drawable.toBitmap()
If you are trying to get bitmap from Glide loaded image then this will help you
Drawable dr = ((ImageView) imView).getDrawable();
Bitmap bmp = ((GlideBitmapDrawable)dr.getCurrent()).getBitmap();
Take a picture of the ImagView and convert it to a string to send to the server
ImageView ivImage1 = (ImageView ) findViewById(R.id.img_add1_send );
getStringImage( ( ( BitmapDrawable ) ivImage1.getDrawable( ) ).getBitmap( ) ),
public String getStringImage(Bitmap bm){
ByteArrayOutputStream ba=new ByteArrayOutputStream( );
bm.compress( Bitmap.CompressFormat.PNG,90,ba );
byte[] by=ba.toByteArray();
String encod= Base64.encodeToString( by,Base64.DEFAULT );
return encod;
}
SOLUTION
Thanks to #ChandraSekhar's suggestions the issue was that I was passing in an Immutable Bitmap to the canvas constructor. The solution is to create a copy of it when using BitmapFactory.decodeFile();
Bitmap bmp = BitmapFactory.decodeFile(imageURL).copy(Bitmap.Config.ARGB_8888, true);
So I have a bitmap that I am using bitmapFactory.decodeFile() for and this works. I am able to create the bitmap, then I need to create a canvas and this is where things get weird.
Here's the flow of what is happening.
I capture an image, then pass it to functionA that sizes it, and saves it out and returns its file path. ( I am using Phonegap Cordova )
I then pass that URL back to my java and use the previously saved image and manipulate it in functionB
CODE IN QUESTION:
// GET URL TO IMAGE
final JSONObject options = optionsArr.optJSONObject(0);
String imageURL = options.optString("image");
// create image bitmap
Bitmap bmp = BitmapFactory.decodeFile(imageURL);
bmp = Bitmap.createBitmap(bmp,0,0,655,655);
/* Everything works fine until this point */
// create image canvas
Canvas canvas = new Canvas(bmp);
Bitmap one = Bitmap.createBitmap(bmp);
canvas.drawBitmap(one,0,0,null);
I receive no errors, it just hangs. Here's the kick in the pants - if I run another function say functionB first that one works but the other doesn't.
I thought maybe I needed to flush and close my first FileOutputStream, but that didn't seem to have any effect. I've tried different variable names for all elements, bitmaps, canvas, and fileoutputstreams.
here is an example of the full function...
NOTE: Because I am using phonegap / cordova I am returning a string
public String none(JSONArray optionsArr) {
// SET FILE PATH
String filePath = "";
File path = new File(Environment.getExternalStorageDirectory()+"/myApp/");
// TMP.jpg is where we store our temporary version of the image
File NewFilePath = new File(path, "tmp_NBB.jpg");
// CREATE FOLDERS IF NEEDED
try{
boolean success = false;
if(!path.exists()){
success = path.mkdir();
}
if (!success){
Log.d("NONE","Folder not created.");
}
else{
Log.d("NONE","Folder created!");
}
}
catch (Exception e){
e.printStackTrace();
}
// GET URL TO IMAGE
final JSONObject options = optionsArr.optJSONObject(0);
String imageURL = options.optString("image");
// create image bitmap
Bitmap bmp = BitmapFactory.decodeFile(imageURL);
bmp = Bitmap.createBitmap(bmp,0,0,655,655);
// create image canvas
Canvas canvas = new Canvas(bmp);
Bitmap none = Bitmap.createBitmap(bmp);
canvas.drawBitmap(none,0,0,null);
// SAVE IMAGE
try {
// OUTPUT STREAM
FileOutputStream out = new FileOutputStream(NewFilePath);
none.compress(Bitmap.CompressFormat.JPEG, 100, out);
// GET FILE PATH
Uri uri = Uri.fromFile(NewFilePath);
filePath = uri.toString();
try{
out.flush();
out.close();
// RETURN FILE PATH
return filePath;
}
catch (Exception e){
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return filePath;
}
Like I said this works for the first image, but when I attempt to open this image again, based on the returned filepath it chunks out at the create canvas line.
edit: The image path I am using looks like this:
/mtn/sdcard/myApp/tmp.jpg
thoughts?
Bitmap one = Bitmap.createBitmap(bmp);
In the above code bmp is a Bitmap and you are creating another Bitmap object one from bmp.
Remove that line and try by changing
canvas.drawBitmap(one,0,0,null);
to
canvas.drawBitmap(bmp,0,0,null);
Are you sure, the device on which you are running supports image size:655x655? Does bitmap get created?