Convert a bitmap image to a URL and set in Imageview

Asked

Viewed 1,486 times

1

Well I would like to know how to set a URL in an Imageview variable, I do not know if I was clear?

  private final DisplayImageOptions options;

public NoticiasAdapter(Activity activity, List objects) {
    super(activity, R.layout.noticia_list_item , objects);
    this.activity = activity;
    this.stocks = objects;

    options = new DisplayImageOptions.Builder()
    .cacheInMemory(true)
    .cacheOnDisk(true)
    .build();
}


public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    StockQuoteView sqView = null;

    if(rowView == null)
    {

        LayoutInflater inflater = activity.getLayoutInflater();
        rowView = inflater.inflate(R.layout.noticia_list_item, null);


        sqView = new StockQuoteView();
         //sqView.quote = (TextView) rowView.findViewById(R.id.ticker_symbol);
        sqView.ticker = (TextView) rowView.findViewById(R.id.ticker_price);
        sqView.img  = (ImageView) rowView.findViewById(R.id.img);     

        rowView.setTag(sqView);
    } else {
        sqView = (StockQuoteView) rowView.getTag();
    }



    Noticias currentStock = (Noticias) stocks.get(position);
    String imagem3 = currentStock.getImagem();

    sqView.ticker.setText(currentStock.getTitulo());
    ImageLoader.getInstance().displayImage(imagem3, sqView.img, options);
  return rowView;
}

protected static class StockQuoteView {
    protected TextView ticker;
    protected TextView quote;
    protected ImageView img;
}
  • You want an Imageview that loads images of Urls from the internet?

  • That’s right...

  • Hello, that question has been asked and answered here: http://answall.com/questions/39883/display-uma-imagem-atrav%C3%A9s-de-url/39895#39895

  • Hello, I saw the answer, I think the answer they gave me was clearer, no?

  • 1

    @Gustavo wrote an answer that can help you!

2 answers

2

This is a simple and direct way to perform the requested procedure.

1 - Create a folder where your images will be, put this code in the main activity:

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
             File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"/MeuApp/imagens/");
                directory.mkdirs();

        } 

2 - Create a private method called getBitmapFromURL, to "grab" the image from a url:

private Bitmap getBitmapFromURL(String url) {
    try {
        URL src = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) src.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

3 - Create a method that will receive the converted Bitmap to save to your device:

private void salvando(Bitmap abmp){

    String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
            "/MeuApp/imagens/";
            File dir = new File(file_path);
            if(!dir.exists())
            dir.mkdirs();
            File file = new File(dir, "nomedaImagembaixada");
            FileOutputStream fOut;
            try {
            fOut = new FileOutputStream(file);
            ;
            abmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
            fOut.flush();
            fOut.close();

            } catch (Exception e) {
            e.printStackTrace();
            }


}

4 - This code will execute the download, as it will pass a return to the method salvando():

salvando(getBitmapFromURL(www.meusite.com.br/imagens/minhaimagens.png));

5 - NOW YES YOU HAVE A URI!

Uri imagemURI = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/MeuApp/imagens/" + "nomedaImagembaixada" );

6 - Finally what you wanted in Imageview:

imgview.setImageUri(imagemURI);

OBS: Caso queira mais de uma imagem: Substitua a 'nomedaImagembaixada' por uma variável do tipo STRING e a 'www.meusite.com.br/imagens/minhaimagens.png', TAMBÉM. Assim, cada valor dado, a ambas as variáveis, servirão para gerar novas imagens. 
  • Worked??????

  • I have no way to test at the moment, but I’ll do it, thank you very much = D

  • Any doubt, put here in the comment, because it takes a few more things, but I imagine you know how to do :)

  • All right, thanks a lot :)

  • How do I take the images and show in Listview later, since they will have different names...

  • 1

    Replace the 'filename' with a variable of type STRING and 'www.meusite.com.br/images/minhaimagens.png', ALSO. Thus, each given value, to both variables, will serve to generate new images.

  • But that way the images wouldn’t all have the same name, no problem?

  • They will not have the same name if you use a logic to vary this variable of the type String I mentioned, as each Imageview :)

  • There is no way I can help you beyond this without understanding what you want, further. I have to see the layout, the purpose of your app... You need to put the full xml codes and etc...

  • Ahh right, I thought of using a counter and adding the number to the image name, but I’m doubtful if the variable is destroyed every call by Listview...

  • 1

    Then you will need to create a position for each image. Creating an adapter.

  • Moderators don’t like that kind of talk that distorts the answer. I advise you to create a new question, INSERTING ALL YOU HAVE OF CODE.

  • All right, I’ll create another question by entering the code...

Show 8 more comments

1


You can utilize the Universal Image Loader, which does all the heavy lifting for you in a fast and effective way.

To implement it in your project is simple:

1) Lower the . jar at this link and import into the "libs" folder of your project

2) In its Application (if you don’t have a, see how to create here) within the method onCreate, initialize the settings for ImageLoader:

...

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
        .threadPriority(Thread.NORM_PRIORITY - 2)
        .threadPoolSize(3)
        .diskCacheExtraOptions(480, 320, null)
        .tasksProcessingOrder(QueueProcessingType.LIFO)
        .build();

ImageLoader.getInstance().init(config);

...

3) To implement within a ListView, for example, configure your Adapter as follows:

private final DisplayImageOptions options;

public SeuAdapter (List<SeusObjetos> list){
    ...

    options = new DisplayImageOptions.Builder()
        .cacheInMemory(true)
        .cacheOnDisk(true)
        .build();
}

public View getView(int position, View convertView, ViewGroup parent) {

    ...
    String suaUrl = "algumaUrl";
    ImageLoader.getInstance().displayImage(suaUrl, suaImageView, options);
    ...

    return convertView;

}

Of course, you will make the implementations that meet your needs on DisplayImageOptions. Explore the documentation of this library to understand and implement what suits you best

  • Thanks, I’ll try what you suggested too...

  • You are asking me to create these classes: Imageloaderconfiguration, Queueprocessingtype and Imageloader.. This is right necessary, or I did something wrong?

  • 1

    Did you put the library into the project? Imported the right classes into your Application?

  • The screen turns white, neither the titles nor the images, you have any idea what could be going wrong?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.