This seems simple, I am trying to set a bitmap image but from the resources, I have within the application in the drawable folder.
bm = BitmapFactory.decodeResource(null, R.id.image);
Is this correct?
Assuming you are calling this in an Activity class
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
The first parameter, Resources, is required. It is normally obtainable in any Context (and subclasses like Activity).
Try this
This is from sdcard
ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/test2.png");
image.setImageBitmap(bMap);
This is from resources
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
If the resource is showing and is a view, you can also capture it. Like a screenshot:
View rootView = ((View) findViewById(R.id.yourView)).getRootView();
rootView.setDrawingCacheEnabled(true);
rootView.layout(0, 0, rootView.getWidth(), rootView.getHeight());
rootView.buildDrawingCache();
Bitmap bm = Bitmap.createBitmap(rootView.getDrawingCache());
rootView.setDrawingCacheEnabled(false);
This actually grabs the whole layout but you can alter as you wish.
If you have declare a bitmap object and you want to display it or store this bitmap object. but first you have to assign any image , and you may use the button click event, this code will only demonstrate that how to store the drawable image in bitmap Object.
Bitmap contact_pic = BitmapFactory.decodeResource(
v.getContext().getResources(),
R.drawable.android_logo
);
Now you can use this bitmap object, whether you want to store it, or to use it in google maps while drawing a pic on fixed latitude and longitude, or to use some where else
just replace this line
bm = BitmapFactory.decodeResource(null, R.id.image);
with
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.YourImageName);
I mean to say just change null value with getResources() If you use this code in any button or Image view click event just append getApplicationContext() before getResources()..
Using this function you can get Image Bitmap. Just pass image url
public Bitmap getBitmapFromURL(String strURL) {
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Related
In my project I used (Volley + NetworkImageView) to download some images and texts and showing them in a list view.. till here, I don't have any problem.
Now, I want to get bitmaps form NetworkImageView and I tried many methods like the following, but non of them worked for me.
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Another method:
imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
Non of them worked..
Any Help is appreciated,,
You cannot get the Bitmap reference as it is never saved in the ImageView.
however you can get it using :
((BitmapDrawable)this.getDrawable()).getBitmap();
beacuse when you set it with Volley u do this:
/**
* Sets a Bitmap as the content of this ImageView.
*
* #param bm The bitmap to set
*/
#android.view.RemotableViewMethod
public void setImageBitmap(Bitmap bm) {
// Hacky fix to force setImageDrawable to do a full setImageDrawable
// instead of doing an object reference comparison
mDrawable = null;
if (mRecycleableBitmapDrawable == null) {
mRecycleableBitmapDrawable = new ImageViewBitmapDrawable(
mContext.getResources(), bm);
} else {
mRecycleableBitmapDrawable.setBitmap(bm);
}
setImageDrawable(mRecycleableBitmapDrawable);
}
however if you set your default image or error image or any other image in any other way you may not get BitmapDrawable but NinePatchDrawable for example.
here is how to check:
Drawable dd = image.getDrawable();
if(BitmapDrawable.class.isAssignableFrom(dd.getClass())) {
//good one
Bitmap bb = ((BitmapDrawable)dd).getBitmap();
} else {
//cannot get that one
}
hey I customize google map makers as an image in my android app , it's working fine but currently it takes time to load markers since there are many markers around 200. Actually, i get the images from backend (parse.com) and then crop it to fit marker shape.
Is there any way to load markers faster?
View marker2 = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.marker, null);
ImageView numTxt = (ImageView) marker2.findViewById(R.id.num_txt);
Bitmap bitmap1 = getBitmap(url1, MapActivity.this);
numTxt.setImageBitmap(bitmap1);
markerOpts = markerOpts.title("Company").snippet("branch").icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(MapActivity.this, marker2)));
public static Bitmap getBitmap(String url2, Context context) {
FileCache fileCache = new FileCache(context);
MemoryCache memoryCache = new MemoryCache();
File f = fileCache.getFile(url2);
//from SD cache
//CHECK : if trying to decode file which not exist in cache return null
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download image file from web
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url2);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
// Constructs a new FileOutputStream that writes to file
// if file not exist then it will create file
OutputStream os = new FileOutputStream(f);
// See Utils class CopyStream method
// It will each pixel from input stream and
// write pixels to output stream (file)
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
//Now file created and going to resize file with defined height
// Decodes image and scales it to reduce memory consumption
b = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
public static Bitmap createDrawableFromView(Context context, View view) {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
Yes, there is. You know for sure that you will need the pictures, so do that in an un-obtrusive way. Load them in the background once, while initializing. After you have loaded them once, just use them from your local environment. So, improvements:
request the pictures and parse them in a background thread while initializing the software to not bother the user with it
store the pictures when you have successfully extracted them and reuse them locally instead of rerequesting them
You can use image downloading library Picasso.
It will handle image downloading and caching, memory usage, and you can crop an image to whatever size you need. And if you load the same image many times (what you probably do) Picasso will use cached image instead of downloading it every time, so that will speed up all the images downloading process.
To use this library you need to declare it in dependency tree of build.gradle file from app folder of your project in Android Studio, so it will look like this:
dependencies {
//some other dependencies
//...
compile 'com.squareup.picasso:picasso:2.5.2'//add this line
}
Then use it in code:
Picasso.with(MapActivity.this).load(url1).into(numTxt);
I am working on a complex UI design it is like circular wheel containing 10 icons in circular locus. i need to scale every icon as per the device resolution. Please have a look for specific code snippet:-
if (displayWidth<=241) {
bitmap = scaleBimtap(bitmap, 42, 39);
}else if (displayWidth<=320) {
bitmap = scaleBimtap(bitmap, 42, 39);
}else if (displayWidth<=480) {
bitmap = scaleBimtap(bitmap, 52, 44);
}else{
bitmap = scaleBimtap(bitmap, 52, 44);
}
HTC sensation is a 540X960 resolution device. So here is bitmap = scaleBimtap(bitmap, 52, 44); must be chosen in this case but this seems to be wrongly scaled and icons being displayed bigger then. What can i do for this to work.
Image from URL
imageView = new (ImageView)findViewById(R.id.myImage);
Get Image from Url
Bitmap originalBitmap = getBitmapFromURL("http://www.chennaionline.com/home.JPG");
getBitmapFromURL method:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Set bitmap
Bitmap bitmap = Bitmap.createScaledBitmap(originalBitmap, width,
height, false);
imageView.setImageBitmap(bitmap);
Image from Resource File
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
I have a bitmap downloader class which decodes a stream into a Bitmap object.
Can I do something like
Bitmap bitmap;
bitmap = object;
when I do imageview.setImageBitmap(bitmap)
would be the same as imageview.setImageBitmap(object)
Also, is it posible to create multiple instances of bitmap? like:
for(i = 0; i < 10; i++) {
Bitmap bitmap = new Bitmap(); // how to do this?
new BitmapDownloaderAsynctask(bitmap).execute(url);
}
when I do imageview.setImageBitmap(bitmap) would be the same as imageview.setImageBitmap(object)
Yes, it would be the same (as long as object is another instance of Bitmap)
In order to create Bitmap manually, there is a bunch of static methods Bitmap.createBitmap() exist to create bitmaps (Bitmap class)
As an example, here is the easiest way to create a bitmap:
Bitmap bmp = Bitmap.createBitmap(100, 100, Config.ARGB_8888); //100*100 bitmap in ARGB color space
EDIT:
If you need to keep bitmap reference unchanged, you need to decode stream in a separate bitmap and then copy content of this bitmap into your original bitmapHolder. You can do that by drawing on the canvas:
AsyncTask code:
.....
Canvas canvas = new Canvas(bitmapHolder); //this bitmap was passed to AsyncTask
Bitmap tmpBitmap = Bitmap.decodeStream(...);
canvas.drawBitmap(tmpBitmap, 0, 0, null); //this will copy your decoded bitmap into your original bitmap which was passed into AsyncTask
.....
I am making an application in Android, which requires sending bitmap object from one activity and displaying that bitmap object sent on the second activity page. But , I am getting a blank screen
Here is a sample of my code for sending the Bitmap object :-
Intent intent = new Intent(Display2.this, Display3.class);
ImageView iv = (ImageView) findViewById(R.id.imageView1);
Bitmap bitmap = Bitmap.createBitmap(iv.getWidth(), iv.getHeight(), Bitmap.Config.RGB_565);
intent.putExtra("BitmapImage", bitmap);
startActivity(intent);
Now the part of code on second activity to retrieve the sent object and displaying it on screen :-
public class Display3 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bitmap bitmap = (Bitmap)getIntent().getParcelableExtra("BitmapImage");
ImageView myIV = (ImageView) findViewById(R.id.imageView1);
bitmap = bitmap.createBitmap(myIV.getWidth(), myIV.getHeight(), Bitmap.Config.RGB_565);
myIV.setImageBitmap(bitmap);
setContentView(R.layout.display3);
}
}
can anyone suggest whats wrong in this part ?
Thanks !
Bitmap implements Parcelable object, so you could always pass it in the intent like below :
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);
and retrieve it on the other end:
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
this is not good for passing bitmap from one activity to another..
You can simply name you Bitmap as static first.
then create a method like
public static Bitmap getBitmap(){
return bitmap;
}
then you can simply call from other activities,
bitmapexistingclass.getBitmap();
if we use intents for passing bitmap we will get some errors check this question How to pass bitmap from one activity to another
from your code above you are creating an empty bitmap:
ImageView iv = (ImageView) findViewById(R.id.imageView1);
Bitmap bitmap = Bitmap.createBitmap(iv.getWidth(), iv.getHeight(), Bitmap.Config.RGB_565);
I do not see any reason why from this code you'll get anything else then blank black bitmap with hight and width equals to the imageView hight and width
what you are expecting from android to fill drawing in Bitmap itself , you are creating an Empty Bitmap Object with height and width equavalent to ImageView object;
as Bitmap implements Parcelable you can simply put it in bundle and retrive on other Activity
Use below two methods to convert a bitmap to string and vice versa. Then you can pass the string with intents from activity to another activity. I too do the same in my application.
Then we dont need to use ParcelableExtra and serialzable class.
public String convertBitmapToString(Bitmap src) {
if(src!= null){
ByteArrayOutputStream os=new ByteArrayOutputStream();
src.compress(android.graphics.Bitmap.CompressFormat.PNG, 100,(OutputStream) os);
byte[] byteArray = os.toByteArray();
return Base64.encodeToString(byteArray,Base64.DEFAULT);
}
return null;
}
public Bitmap getBitMapFromString(String src){
Bitmap bitmap = null;
if(src!= null){
byte[] decodedString = Base64.decode(src.getBytes(), Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(decodedString,0,decodedString.length);
return bitmap;
}
return null;
}