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="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj03aJkVlOJwJxYpg5H5iOiOBUUhxGP4OnPQ8KIPn4n-YyAkOM6yPJH-J-pIQUXAzGiVu2I8gvfE-rCrFl2MYnl-7COmfJ8CcNje17yH64CTTtUFQO0eRLFBP-kkTE3GmHS4qmIcayCry0d/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());
}
}
6 comments:
thank you for sharing this ode with us
you didn't mention that we should add permition to the manifest file to store on external SD card
sucks badly, hardcoded "sdcard", no AsyncTask ...
What if image already exists in the SDcard???
The method getApplicationContext() is undefined for the type DownloadAndReadImage
i want this project, i copied code but my application didn't show image
Awesome now how does one use this :|
Post a Comment