Introduction
The Bitmap
(android.graphics.Bitmap) class represents a bitmap image. You create bitmaps using the BitmapFactory (android.graphics.BitmapFactory) class. Bitmaps can be created using BitmapFactory from a resource, a file, or an InputStream.
From file
Pass path to the image to BitmapFactory.decodeFile()
to load the image previously copied to the sdcard. The BitmapFactory creates a bitmap object with this image. Use the ImageView.setImageBitmap()
method to update the ImageView component.
public class LoadImages extends Activity { @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/test.png"); image.setImageBitmap(bMap); } }
From input stream
Create the input stream for BitmapFactory.decodeStream()
using Java FileInputStream and BufferedInputStream. Use BitmapFactory.decodeStream() to convert a BufferedInputStream into a bitmap object.
public class LoadImages extends Activity { @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/test.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()); } } }
From project resource
Use BitmapFactory.decodeResource(res, id)
to get a bitmap from an Android resource.
public class LoadImages extends Activity { @Override 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); } }