Jpg from url android

Android. Вывод изображений, различные способы

Эта статья будет полезна начинающим разработчикам, здесь я предложу несколько вариантов вывода изображений на Android. Будут описаны следующие способы:

Обычный метод – стандартный способ, используя ImageView. Рассмотрены варианты загрузки картинки из ресурса, а также из файла на SD карте устройства.

Продвинутый вариант — вывод изображения, используя WebView. Добавляется поддержка масштабирования и прокрутки картинки при помощи жестов.

“Джедайский” способ – улучшенный предыдущий вариант. Добавлен полноэкранный просмотр с автоматическим масштабированием изображения при показе и поддержкой смены ориентации устройства.

Исходники тестового проекта на GitHub github.com/Voldemar123/andriod-image-habrahabr-example

В этой статье я не рассматриваю вопросы загрузки изображений из Интернета, кеширования, работы с файлами и необходимых для работы приложения permissions – только вывод картинок.

Итак, задача — предположим, в нашем приложении необходимо вывести изображение на экран.
Картинка может размерами превышать разрешение экрана и иметь различное соотношение сторон.
Хранится она либо в ресурсах приложения, либо на External Storage — SD карте.

Также допустим, мы уже записали на карту памяти несколько изображений (в тестовом проекте – загружаем из сети). Храним их в каталоге данных нашего приложения, в кеше.

public static final String APP_PREFS_NAME = Constants.class.getPackage().getName();
public static final String APP_CACHE_PATH =
Environment.getExternalStorageDirectory().getAbsolutePath() +
«/Android/data/» + APP_PREFS_NAME + «/cache/»;

Layout, где выводится картинка

android:layout_width=»match_parent»
android:layout_height=»match_parent»
android:orientation=»vertical» >

Масштабирование по умолчанию, по меньшей стoроне экрана.
В Activity, где загружаем содержимое картинки

private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageView1);

Из ресурсов приложения (файл из res/drawable/img3.jpg)

Задавая Bitmap изображения

FileInputStream fis = new FileInputStream(Constants.APP_CACHE_PATH + this.image);
BufferedInputStream bis = new BufferedInputStream(fis);

Bitmap img = BitmapFactory.decodeStream(bis);

Или передать URI на изображение (может хранится на карте или быть загружено из сети)

mImageView.setImageURI( imageUtil.getImageURI() );
Uri.fromFile( new File( Constants.APP_CACHE_PATH + this.image ) );

Этот способ стандартный, описан во множестве примеров и поэтому нам не особо интересен. Переходим к следующему варианту.

Предположим, мы хотим показать большое изображение (например фотографию), которое размерами превышает разрешение нашего устройства. Необходимо добавить прокрутку и масштабирование картинки на экране.

android:layout_width=»match_parent»
android:layout_height=»match_parent»
android:orientation=»vertical» >

В Activity, где загружаем содержимое

protected WebView webView;
webView = (WebView) findViewById(R.id.webView1);

установка черного цвета фона для комфортной работы (по умолчанию – белый)

включаем поддержку масштабирования

больше места для нашей картинки

webView.setPadding(0, 0, 0, 0);

полосы прокрутки – внутри изображения, увеличение места для просмотра

загружаем изображение как ссылку на файл хранящийся на карте памяти

webView.loadUrl(imageUtil.getImageFileLink() );
«file:///» + Constants.APP_CACHE_PATH + this.image;

Теперь мы хотим сделать так, чтобы картинка при показе автоматически масштабировалась по одной из сторон, при этом прокрутка остается только в одном направлении.
Например, для просмотра фотографий более удобна ландшафтная ориентация устройства.
Также при смене ориентации телефона масштаб изображения должен автоматически меняться.
Дополнительно расширим место для просмотра изображения на полный экран.

В AndroidManifest.xml для нашей Activity добавляем

В код Activity добавлен метод, который вызыватся при каждом повороте нашего устройства.

@Override
public void onConfigurationChanged(Configuration newConfig) <
super.onConfigurationChanged(newConfig);
changeContent();
>

В приватном методе описана логика пересчета масштаба для картинки
Получаем информацию о размерах дисплея. Из-за того, что мы изменили тему Activity, теперь WebView раскрыт на полный экран, никакие другие элементы интерфейса не видны. Видимый размер дисплея равен разрешению экрана нашего Android устройства.

Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

int width = display.getWidth();
int height = display.getHeight();

Читайте также:  Режим самолет андроид отключить

Размеры изображения, выбранного для показа

Bitmap img = imageUtil.getImageBitmap();

int picWidth = img.getWidth();
int picHeight = img.getHeight();

Меняем масштаб изображения если его высота больше высоты экрана. Прокрутка теперь будет только по горизонтали.

if (picHeight > height)
val = new Double(height) / new Double(picHeight);

Подбрасываем в WebView специально сформированный HTML файл, содержащий изображение.

webView.loadDataWithBaseURL(«/»,
imageUtil.getImageHtml(picWidth, picHeight),
«text/html»,
«UTF-8»,
null);

StringBuffer html = new StringBuffer();

Такой способ я применил из-того, что после загрузки изображения в WebView через метод loadUrl, как в прошлом варианте, setInitialScale после поворота устройства не изменяет масштаб картинки. Другими словами, показали картинку, повернули телефон, масштаб остался старый. Очень похоже на то, что изображение как-то кешируется.

Я не нашел в документации упоминания об этом странном поведении. Может быть местные специалисты скажут, что я делаю не так?

Источник

Learn2Crack

Android Load Image from Internet (URL) – Example

Sometimes you may need to load an Image from URL in your Android app. If you are searching for a way, this tutorial shows you how to do this with less effort.

Here I have created an Android Studio project with package com.learn2crack.loadimageurl also Activity as MainActivity and layout as activity_main.

Adding Required Permissions

We need to add Internet permission in our AndroidManifest.xml.

Our activity layout has a Button and an ImageView to display the image.

Loading image via the Internet is time-consuming and if done in the main thread it makes the UI unresponsive . So we use AsyncTask to do this in a background thread. The decodeStream() method of the BitmapFactory class is used to load the image. We create a Listener interface to pass the image to Main Activity. The onImageLoaded() method will be called if the image is fetched successfully. The onError() method will be called if an error occurs.

The MainActivity implements the Listener interface. The fetched bitmap is set to ImageView using setImageBitmap() method. If an error occurs a Toast is displayed.

Try this in an Emulator or your own device.

Complete Project Files

You can download the complete project as zip or fork from our Github repository.

Note :
Last Updated On : Oct 15, 2016

Источник

Android Loading Image from URL (HTTP)

I am writing this tutorial as lot of people are asking me about loading an image into imageview. Just by adding url to ImageView won’t load directly. Instead we need to store the image into cache (temporary location) and attach to ImageView. This can be achieved just by calling couple of lines and don’t forget to add required classes to your project.

1. Create a new project in Eclipse IDE by navigating to File ⇒ New ⇒ Android Project and fill the required details.
2. Inorder to load images from an url we first need to store the image in a temporary location and once it is downloaded it should be added to ImageView. To create a temporary file we need to access device external storage. Add required permission to AndroidManifest.xml file.

To access internet required permission is – INTERNET
To access external storage required permission is – WRITE_EXTERNAL_STORAGE

3. For testing purpose create a simple ImageView in your main.xml file

4. Open your main activity and type the following code. Whenever you wan’t to show an image from url just call the following code.

5. Add following classes in your project and run the project.

Required Classes

ImageLoader.java

Читайте также:  Как найти удаленное управление андроид

FileCache.java

Utils.java

Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: [email protected]

Android Integrating PayTM Payment Gateway – ECommerce App

Android Integrating Google’s reCAPTCHA in your App

Android Content Placeholder Animation like Facebook using Shimmer

hello, thank you for tutorial. Unfortunately, it works for me only on emulator and when i install it on my phone, images won’t load. Why does this happen?

and I need to tell that i have 83 mb of free memory on SD card and 50 mb free internal memory

Can Someone help me how can i integrate progressbar in this code? please!

realy thanks man… works fine…

There is a problem with the ImageLoader class. You see, when I added the BitmapFactory.Options o2 under decodeFile(File f) method, I get an “Unreachable Code” error status. What should I do?

no image will be show only loader image is shown help me whats the problem

Raise the REQUIRED_SIZE.

This tutorial is the worst! It is due by updates, instead of the image loaded properly from the URL, I got corrupted image as a result. Look at my sample.

hello..i have to load images & and data from webservices…can u plz help me….

this is what you want

@pratik butani. how to load info like(username ,intrest,gender ,,) in this code

u can use universal image loader library for that…………….

I want to display image in ListVIew From PHP Server or web server .
But I need to set my Enulator HeapSize more than 32 MB. It Generate Errors.
Can I Use Above Code to Display Image in List View From Server.
Help Me.
I am your website great FAN.

Hi
this tutorial is so good
i read about a lib for developer games in android [libgdx]
can you do tutorials about this?

i want to show image in large size so i replace _s by _n but it save it as small,as follow:
String _n=_s.replace(“_s.jpg”, “_n.jpg”);
imageLoader2.DisplayImage(_n, picture);

plz could any one help me?

break the json into pices until you get the url

@anonim …..plzzzz explain how to code to get (username ,…gender,…etc) i m also using json webservic url . aftr login

Hi Ravi
This tutorial is very helpful to me please post the dynamic grid view (Images from server) at least please give me a sugeestions

Please give me code to display multiple images from MYSQL DB with help of php webservice

hi did u got solution of that image blurred .

With the same code when i replace image url it throws FileNotFound Exception . i m stuck with it. Any idea?

sir i have same problem
and i have already add this permision

Thnaks this is very helpful..

Hi Ravi… Its Fantastic Tutorial.. Thanks a lot.

Here I want to Update Image directly in My Folder, how can i update without passing ImageVIew object.

i have tried like this:

It’s giving me Error…

what can i do… Please Reply me…

Hello sir i am getting too many redirects exception please help me out.

hi ravi …great tutorial ….thankz for this..

then can you provide the API php code for how can i add image to my database and retrieve from it and send to my android app using json…..

Hi Ravi, I haven’t tried this yet, but I want to know if I can use this for populating listview with images? Thanks!

Читайте также:  Как разблокировать приставку андроид

hi ravi …can i also use this .code to show profile information(user name,intresrt,gender…user_image….) aftr login……..from the webservice

Hi Ravi,
How can i set size image from your project, image downloaded and show on device too small than this link:
Thanks so much

That would be nicer if you actually wrote this code.

Hi, thanx for the good tutorial but i want to load multiple images ho to do that?

Pls help me out!
Why i use this link:
above sample can’t load image, return bitmap=null;

Reading image from URL can be performed inside AsynTask as it should not affect the current Activity. Using AysnTask will run downloading image from URL as separate thread.
Regards,
Udhay
http://programmerguru.com

Hi, How to store the Images in internal memory of the phone? In this tutorial we are using External memory for cache

hi , The tutorial helped me a lot…

I have one question though.. Where can I change the size of the image which is downloaded?

did not works with images in a listview

GREAT TUTORIAL i use it to my app – its work perfect!:)
i m asking your help guys
i use my personal String url – JSON that i downloads about 500 images from my Json!
when i scroll the list view fast i
MUST HAVE A SPINNER PROGRESS BAR IN EVERY ROW IN THE LIST VIEW UNTIL THE IMAGE SHOW/COMPLIT –
PLEASE HELP ME WITH THIS

This might help

hi. What is R.drawable.loader? I ask because my program does not recognize it

It is an image name exists in the drawable folder

Its working but i am unable to understand this code. It would be lot better if you explain the working of this project.
Thanks

nice this is so good

Hi Ravi, where do i need to recycle the bitmap? im having trouble whenever i re-open my app using these codes. it says out of memory. thanks

Hi, may i know what is the R.drawable.loader. If it was a code/ image may i have it cause i dont have it on my drawable folder. Thanks in advance.

Got it, just an image.

Im using a fragment and this how i use it:

ImageLoader imgLoader = new ImageLoader(getActivity().getApplicationContext());

public void DisplayImage(String url, int loader, ImageView imageView)
<
stub_id = loader;
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
<
queuePhoto(url, imageView);
imageView.setImageResource(loader);
>
>
And im getting an error when i call the java class. What is the problem on my code?

ImageLoader imgLoader = new ImageLoader(getActivity() );

hi ravi i want to know ….i want to set image in circle …i m using this code …..so whare to edit ..what to edit in code…..plzzzz rply fast

Very helpful, thanks

i ravi i m using this code its working i have i query ….i want to display image in size as i want …….can u tell me how to increse/decrease size of image which is comming from url

i ravi i m using this code its working i have i query ….i want to display image in size as i want …….can u tell me how to increse/decrease size of image which is comming from url….plzz reply fast

What if I want to make the extension of string image_url automatically detect whether .jpg or .png?
// Image url
String image_url = “http://api.androidhive.info/images/sample.jpg”; // or png?

I’m confused with this function”boolean imageViewReused(PhotoToLoad photoToLoad)”,could you tell me what it is used for?

Источник

Оцените статью