I want to create a dynamic image view where every image in my gallery will going to use bitmapfactory and not image drawable that binds in the image view. Is there some sites that has bitmapfactory tutorial for this? i believe that using bitmapfactory uses less memory that binding the image into image view? Is this right? I want also to minimize the risk of memory leaks thats why I want to use bitmapfactory. Please help. I cant find basic examples that teaches bitmapfactory.
Building Bitmap Objects
1) From a File
Use the adb tool with push option to copy test2.png onto the sdcard
This is the easiest way to load bitmaps from the sdcard. Simply pass the path to the image to BitmapFactory.decodeFile() and let the Android SDK do the rest.
public class TestImages extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/test2.png");
image.setImageBitmap(bMap);
}
}
All this code does is load the image test2.png that we previously copied to the sdcard. The BitmapFactory creates a bitmap object with this image and we use the ImageView.setImageBitmap() method to update the ImageView component.
2) From an Input stream
Use BitmapFactory.decodeStream() to convert a BufferedInputStream into a bitmap object.
public class TestImages extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
FileInputStream in;
BufferedInputStream buf;
try {
in = new FileInputStream("/sdcard/test2.png");
buf = new BufferedInputStream(in);
Bitmap bMap = BitmapFactory.decodeStream(buf);
image.setImageBitmap(bMap);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
}
}
This code uses the basic Java FileInputStream and BufferedInputStream to create the input stream for BitmapFactory.decodeStream(). The file access code should be surrounded by a try/catch block to catch any exceptions thrown by FileInputStream or BufferedInputStream. Also when you're finished with the stream handles they should be closed.
3) From your Android project's resources
Use BitmapFactory.decodeResource(res, id) to get a bitmap from an Android resource.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
image.setImageBitmap(bMap);
}
Related
I have some jpeg file stored into application private storage. I'm showing them in an ImageView and everything works properly.
But for some jpeg, with sizes similar to the others, BitmapFactory.decodeFile returns null.
This happens with all jpegs generated by Microsoft Paint: just by taking a jpeg that works well, loading into msPaint and saving it unmodified, to get a not working jpeg.
This is the code (the filepath and filename are properly set because it works for many files):
...
public class MainActivity extends ActionBarActivity {
...
private ImageView myImage;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myImage = (ImageView) findViewById(R.id.imageView1);
File f=new File(basedir, list.get(imageIndex).getFile());
Bitmap b = BitmapFactory.decodeFile(f.getPath());
if (b != null){
myImage.setImageBitmap(b);
} else {
myImage.setImageResource(R.drawable.default);
}
...
}
...
}
I've also tried FileInputStream, as suggested somewhere else but with the same result:
...
File f=new File(basedir, list.get(imageIndex).getFile());
FileInputStream fis = new FileInputStream(f);
Bitmap b = BitmapFactory.decodeStream(fis);
if (b != null){
myImage.setImageBitmap(b);
} else {
myImage.setImageResource(R.drawable.default);
}
...
Does BitmapFactory have any known limitation? Is there any way to check jpeg characteristics??
I'm new to android programming and have been trying to figure out how to
load an image (at startup) from the assets folder and save that image in a object (What kind of object should i save it into?)
So that when i want to display that object in an imageview i can just point to it and retreve an imageview displaying that image.
I tryed looking for similar posts but there was nothing specific enough for me to understand fully.
Is there any way to do this or is it a completely wrong approach to using images in android?
Thanks in advance
Here is the code you need. It gets the AssetManager, reads a bitmap from assets, and places the bitmap in an image view.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the AssetManager
AssetManager manager = getAssets();
// Read a Bitmap from Assets
try {
InputStream open = manager.open("icon.png");
Bitmap bitmap = BitmapFactory.decodeStream(open);
// Assign the bitmap to an ImageView in this layout
ImageView view = (ImageView) findViewById(R.id.ImageView01);
view.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
The onCreate method runs when the activity is created. The content view is set and then the AssetManager is retrieved. The AssetManager opens the image "icon".png and saves it as a bitmap. The bitmap can now be assigned to imageviews.
I have a small query, is it possible to get an image dynamically every-time the app is launched over the internet and then that Image can be used to be shown on UI(via xml file)please let me know if this can be achieved in android and with any sample code.
Thanks & Regards.
In this case the best way to do it is to load image via HTTP GET, store it in Bitmap object and inject programmatically into ImageView element defined in layout.
You can't override resource image so you cant use #drawable.
Here you have loadBitmap method that loads image by url and stores it in Bitmap: How to load an ImageView by URL in Android?
Next thing is to inject it into ImageView:
ImageView image = (ImageView) findViewById(R.id.image);
Bitmap bitmap = loadBitmap("http://www.android.com/images/logo.png");
image.setImageBitmap(bitmap);
Not possible through XML.
I'd recommend having a placebo bitmap also in case there is no Internet access available at the time. Use AsyncTask when downloading.
new GetAndSetBitmap.execute(url)
private class GetAndSetBitmap extends AsyncTask<String, Void, Bitmap>
{
protected Bitmap doInBackground(String... urls)
{
Bitmap bitmap = loadBitmap(url[0]);
// Used the loadBitmap from other answer. Anything goes wrong
// load a local resource with the same dimensions.
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bm)
{
yourImageView.setImageBitMap(bm);
}
}
Guys found a better solution
try {
ImageView i = (ImageView)findViewById(R.id.image);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I have saved a image in internal memory. For example I saved it as test.jpg. Now I want to show it in a imageview. I have tried this:
ImageView img = (ImageView)findViewById(R.id.imageView1);
try {
img.setImageDrawable(Drawable.createFromPath("test.jpg"));
} catch (Exception e) {
Log.e(e.toString());
}
And get the following message in LogCat:
SD Card is available for read and write truetrue
Any help or reference please?
public class AndroidBitmap extends Activity {
private final String imageInSD = "/sdcard/er.PNG";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
ImageView myImageView = (ImageView)findViewById(R.id.imageview);
myImageView.setImageBitmap(bitmap);
}
}
or
final Bitmap bm = BitmapFactory.decodeStream( ..some image.. );
// The openfileOutput() method creates a file on the phone/internal storage in the context of your application
final FileOutputStream fos = openFileOutput("my_new_image.jpg", Context.MODE_PRIVATE); // Use the compress method on the BitMap object to write image to the OutputStream
bm.compress(CompressFormat.JPEG, 90, fos);
hope it works...
Take a look at the doc..
You don't need to "know" where the image is stored. You just need to hold on to what you saved it as, and then you can read it back again.
The question is... did you save the file there? Or are you confusing this with images that you have compiled into the application? If it's the latter, the documentation also talks about how to read those, they are not the same as files that you have written to the device, they're part of the app package.
Welcome to Stack! If you find answers useful don't forget to upvote them and mark them as "correct" if they solve your problems.
Cheers.
I'm writing an app that stores a String in an SQLite database, which represents the filepath of an image on the /sdcard/. I have this code in the onCreate() one of my activities:
final Intent receivedIntent = getIntent();
String imageStr = receivedIntent.getExtras().getString("picture");
ImageView imageView = (ImageView) findViewById(R.id.pPicture);
File file = new File (imageStr);
if (file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(imageStr);
imageView.setImageBitmap(bitmap);
}
The code works when I'm first loading the activity, but when I switch between screen orientations, it crashes my application. Any ideas on what I can do to fix this? I'd like to bee able to continue switching between orientations, but I don't need to refresh each time.
Also, I'm somewhat new, so please try to keep your answers not too complicated if possible.
Note that the file does exist in all cases.
I think your app crashes because of OutOfMemoryException. Try recylcing the bitmap in onDestroy():
#Override
public void onDestroy() {
super.onDestroy();
ImageView imageView = (ImageView) findViewById(R.id.pPicture);
Drawable drawable = imageView.getDrawable();
imageView.setImageDrawable(null);
if (drawable instanceof BitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
bitmap.recycle();
bitmap = null;
}
}