Convert String Url To Bitmap: How To Download An Image in ANDROID Programatically
Convert String Url To Bitmap: How To Download An Image in ANDROID Programatically
private Bitmap getImageBitmap(String url) { Bitmap bm = null; try { URL aURL = new URL(url); URLConnection conn = aURL.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); bm = BitmapFactory.decodeStream(bis); bis.close(); is.close(); } catch (IOException e) { Log.e(TAG, "Error getting bitmap", e); } return bm; }
public class DownloadImage extends Activity { private final String PATH = "/data/data/pack.coderzheaven/"; TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv = (TextView)findViewById(R.id.tv); DownloadFromUrl(PATH+"dwn_img.jpg"); } public void DownloadFromUrl(String fileName) {
try { URL url = new URL("http://discounttravel.vn/Uploads/cityavatar/DT_mobile_DaLat_img.jpg"); //you can write here any link File file = new File(fileName); long startTime = System.currentTimeMillis(); tv.setText("Starting download......from " + url); URLConnection ucon = url.openConnection(); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); /* * Read bytes to the Buffer until there is nothing more to read(1). */ ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } FileOutputStream fos = new FileOutputStream(file); fos.write(baf.toByteArray()); fos.close(); tv.setText("Download Completed in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec"); } catch (IOException e) { tv.setText("Error: " + e); } } } <uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></usespermission> <uses-permission android:name="android.permission.READ_PHONE_STATE"></usespermission>