DownloadAndReadImage.java
public class DownloadAndReadImage
{
String strURL;
int pos;
Bitmap bitmap=null;
// pass image url and Pos for example i:
DownloadAndReadImage(String url,int position)
{
this.strURL=url;
this.pos=position;
}
public Bitmap getBitmapImage()
{
downloadBitmapImage();
return readBitmapImage();
}
void downloadBitmapImage()
{
InputStream input;
try {
URL url = new URL (strURL);
input = url.openStream();
byte[] buffer = new byte[1500];
OutputStream output = new FileOutputStream ("/sdcard/"+pos+".png");
try
{
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0)
{
output.write(buffer, 0, bytesRead);
}
}
finally
{
output.close();
buffer=null;
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();
}
}
Bitmap readBitmapImage()
{
String imageInSD = "/sdcard/mac/"+strURL;
BitmapFactory.Options bOptions = new BitmapFactory.Options();
bOptions.inTempStorage = new byte[16*1024];
bitmap = BitmapFactory.decodeFile(imageInSD,bOptions);
return bitmap;
}
}
MainActivity.java
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String imgURL="http://4.bp.blogspot.com/-GDG0jraKnFI/TzZHQ5At0zI/AAAAAAAAAEY/TPl4U6vm5lw/s1600/android-example-code-demo-program.jpg";
ImageView ivCurrent;
ivCurrent = (ImageView)findViewById(R.id.imageview1);
// calling DownloadAndReadImage class to load and save image in sd card
DownloadAndReadImage dImage= new DownloadAndReadImage(imgURL,1);
ivCurrent.setImageBitmap(dImage.getBitmapImage());
}
}


1 comments:
Post a Comment