java - resource - imageview bitmap android
Carga de Android desde la URL al mapa de bits (13)
De manera muy rápida, este método funciona muy rápido:
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
Tengo una pregunta sobre cómo cargar una imagen desde un sitio web. El código que uso es:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Bitmap bit=null;
try {
bit = BitmapFactory.decodeStream((InputStream)new URL("http://www.mac-wallpapers.com/bulkupload/wallpapers/Apple%20Wallpapers/apple-black-logo-wallpaper.jpg").getContent());
} catch (Exception e) {}
Bitmap sc = Bitmap.createScaledBitmap(bit,width,height,true);
canvas.drawBitmap(sc,0,0,null);
Pero siempre devuelve una excepción de puntero nulo y el programa falla. La URL es válida y parece funcionar para todos los demás. Estoy usando 2.3.1.
Pase su URL de imagen: intente esto:
private Bitmap getBitmap(String url)
{
File file=fileCache.getFile(url);
Bitmap bm = decodeFile(file);
if(bm!=null)
return bm;
try {
Bitmap bitmap=null;
URL ImageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)ImageUrl.openConnection();
conn.setConnectTimeout(50000);
conn.setReadTimeout(50000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(file);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(file);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
private Bitmap decodeFile(File file){
try {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(file),null,opt);
final int REQUIRED_SIZE=70;
int width_tmp=opt.outWidth, height_tmp=opt.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
BitmapFactory.Options opte = new BitmapFactory.Options();
opte.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(file), null, opte);
} catch (FileNotFoundException e) {}
return null;
}
Crear Utilidades de Clase:
public class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
}
Por favor, intente estos siguientes pasos.
1) Cree AsyncTask en clase o adaptador (si desea cambiar la imagen del elemento de la lista).
public class AsyncTaskLoadImage extends AsyncTask<String, String, Bitmap> {
private final static String TAG = "AsyncTaskLoadImage";
private ImageView imageView;
public AsyncTaskLoadImage(ImageView imageView) {
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
try {
URL url = new URL(params[0]);
bitmap = BitmapFactory.decodeStream((InputStream) url.getContent());
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
try {
int width, height;
height = bitmap.getHeight();
width = bitmap.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bitmap, 0, 0, paint);
imageView.setImageBitmap(bmpGrayscale);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2) Llame a AsyncTask desde su actividad, fragmento o adaptador (dentro deBindViewHolder).
2.a) Para el adaptador:
String src = current.getProductImage();
new AsyncTaskLoadImage(holder.icon).execute(src);
2.b) Para actividad y fragmento:
**Activity:**
ImageView imagview= (ImageView) findViewById(R.Id.imageview);
String src = (your image string);
new AsyncTaskLoadImage(imagview).execute(src);
**Fragment:**
ImageView imagview= (ImageView)view.findViewById(R.Id.imageview);
String src = (your image string);
new AsyncTaskLoadImage(imagview).execute(src);
3) Por favor, ejecute la aplicación y verifique la imagen.
Feliz codificación ... :)
Prueba esto:
AQuery aq = new AQuery(getActivity());
aq.id(view.findViewById(R.id.image)).image(imageUrl, true, true, 0, 0,
new BitmapAjaxCallback() {
@Override
public void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status){
iv.setImageBitmap(bm);
}
}.header("User-Agent", "android"));
Si carga URL desde mapa de bits sin utilizar AsyncTask, escriba dos líneas después de setContentView (R.layout.abc);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL("http://....");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch(IOException e) {
System.out.println(e);
}
Si está usando Picasso o Universal-Image-Loader para cargar imágenes desde url.
Simplemente puede obtener el mapa de bits cargado por
Para Picasso
Picasso.with(this)
.load(imageUrl)
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// loaded bitmap is here (bitmap)
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
Para Universal-Image-Loader
imageLoader.loadImage(imageUrl, new SimpleImageLoadingListener()
{
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)
{
// loaded bitmap is here (loadedImage)
}
});
Si está usando Picasso para imágenes, puede probar el método a continuación.
public static Bitmap getImageBitmapFromURL(Context context, String imageUrl){
Bitmap imageBitmap = null;
try {
imageBitmap = new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
try {
int targetHeight = 200;
int targetWidth = 200;
return Picasso.with(context).load(String.valueOf(imageUrl))
//.resize(targetWidth, targetHeight)
.placeholder(R.drawable.raw_image)
.error(R.drawable.raw_error_image)
.get();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
}
return imageBitmap;
}
Siga el método para obtener la URL en el mapa de bits en Android, simplemente pase el enlace de esta imagen y obtenga un mapa de bits.
public static Bitmap getBitmapFromURL(String imgUrl) {
try {
URL url = new URL(imgUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
Yo prefiero estos:
Crea Bitmap de InputStream y lo devuelve:
public static Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
}
catch (IOException e1) {
e1.printStackTrace();
System.out.println("downloadImage"+ e1.toString());
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
public static InputStream getHttpConnection(String urlString) throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println("downloadImage" + ex.toString());
}
return stream;
}
RECUERDA :
Android incluye dos clientes HTTP : HttpURLConnection y Apache HTTP Client. Para Gingerbread y más tarde, HttpURLConnection es la mejor opción.
Desde Android 3.x Honeycomb o posterior, no puede realizar Network IO en el hilo de la interfaz de usuario y hacer esto arroja android.os.NetworkOnMainThreadException . Debe usar Asynctask en su lugar como se muestra a continuación
/** AsyncTAsk for Image Bitmap */
private class AsyncGettingBitmapFromUrl extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
System.out.println("doInBackground");
Bitmap bitmap = null;
bitmap = AppMethods.downloadImage(params[0]);
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
System.out.println("bitmap" + bitmap);
}
}
Glide.with(context)
.load("http://test.com/yourimage.jpg")
.asBitmap() // переводим его в нужный формат
.fitCenter()
.into(new SimpleTarget<Bitmap>(100,100) {
@Override
public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
// do something with you bitmap
bitmap
}
});
public Drawable loadImageFromURL(String url, String name) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, name);
return d;
} catch (Exception e) {
return null;
}
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
public static Bitmap getImgBitmapFromUri(final String url, final Activity context, final CropImageView imageView, final File file) {
final Bitmap bitmap = null;
AsyncTask.execute(new Runnable() {
@Override
public void run() {
try {
Utils.image = Glide.with(context)
.load(url).asBitmap()
.into(100, 100).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
context.runOnUiThread(new Runnable() {
@Override
public void run() {
if (imageView != null)
imageView.setImageBitmap(Utils.image);
}
});
}
});
return Utils.image;
}
Use la biblioteca Glide y ejecute el siguiente código en el hilo de trabajo como se publicó