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 после поворота устройства не изменяет масштаб картинки. Другими словами, показали картинку, повернули телефон, масштаб остался старый. Очень похоже на то, что изображение как-то кешируется.
Я не нашел в документации упоминания об этом странном поведении. Может быть местные специалисты скажут, что я делаю не так?
Источник
Sharing Content with Intents
Intents allow us to communicate data between Android apps and implicit intents can also accept actions. One of those actions is the ACTION_SEND command which indicates we want to send data across apps. To send data, all you need to do is specify the data and its type, and the system will identify compatible receiving activities and display them to the user.
Sending and receiving data between applications with intents is most commonly used for social sharing of content. Intents allow users to share information quickly and easily, using their favorite applications.
You can send content by invoking an implicit intent with ACTION_SEND .
To send images or binary data:
Sending URL links should simply use text/plain type:
In certain cases, we might want to send an image along with text. This can be done with:
Sharing multiple images can be done with:
See this stackoverflow post for more details.
Note: Facebook does not properly recognize multiple shared elements. See this facebook specific bug for more details and share using their SDK.
Facebook doesn’t work well with normal sharing intents when sharing multiple content elements as discussed in this bug. To share posts with facebook, we need to:
- Create a new Facebook app here (follow the instructions)
- Add the Facebook SDK to your Android project
- Share using this code snippet:
You may want to send an image that were loaded from a remote URL. Assuming you are using a third party library like Glide, here is how you might share an image that came from the network and was loaded into an ImageView. There are two ways to accomplish this. The first way, shown below, takes the bitmap from the view and loads it into a file.
and then later assuming after the image has completed loading, this is how you can trigger a share:
Make sure to setup the «SD Card» within the emulator device settings:
Note that if you are using API 24 or above, see the section below on using a FileProvider to work around new file restrictions.
If you are targeting Android API 24 or higher, private File URI resources (file:///) cannot be shared. You must instead wrap the File object as a content provider (content://) using the FileProvider class.
First, you must declare this FileProvider in your AndroidManifest.xml file within the tag:
Next, create a resource directory called xml and create a fileprovider.xml . Assuming you wish to grant access to the application’s specific external storage directory, which requires requesting no additional permissions, you can declare this line as follows:
Finally, you will convert the File object into a content provider using the FileProvider class:
If you see a INSTALL_FAILED_CONFLICTING_PROVIDER error when attempting to run the app, change the string com.codepath.fileprovider in your Java and XML files to something more unique, such as com.codepath.fileprovider.YOUR_APP_NAME_HERE .
Note that there are other XML tags you can use in the fileprovider.xml , which map to the File directory specified. In the example above, we use Context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) , which corresponded to the XML tag in the declaration with the Pictures path explicitly specified. Here are all the options you can use too:
XML tag | Corresponding storage call | When to use |
---|---|---|
Context.getFilesDir() | data can only be viewed by app, deleted when uninstalled ( /data/data/[packagename]/files ) | |
Context.getExternalFilesDir() | data can be read/write by the app, any apps granted with READ_STORAGE permission can read too, deleted when uninstalled ( /Android/data/[packagename]/files ) | |
Context.getCacheDir() | temporary file storage | |
Environment.getExternalStoragePublicDirectory() | data can be read/write by the app, any apps can view, files not deleted when uninstalled | |
Context.getExternalCacheDir() | temporary file storage with usually larger space |
If you are using API 23 or above, then you’ll need to request runtime permissions for Manifest.permission.READ_EXTERNAL_STORAGE and Manifest.permission.WRITE_EXTERNAL_STORAGE in order to share the image as shown above since newer versions require explicit permisions at runtime for accessing external storage.
Note: There is a common bug on emulators that will cause MediaStore.Images.Media.insertImage to fail with E/MediaStore﹕ Failed to insert image unless the media directory is first initialized as described in the link.
This is how you can easily use an ActionBar share icon to activate a ShareIntent. The below focuses on the support ShareActionProvider for use with AppCompatActivity .
Note: This is an alternative to using a sharing intent as described in the previous section. You either can use a sharing intent or the provider as described below.
First, we need to add an ActionBar menu item in res/menu/ in the XML specifying the ShareActionProvider class.
Next, get access to share provider menu item in the Activity so we can attach the share intent later:
Note: ShareActionProvider does not respond to onOptionsItemSelected() events, so you set the share action provider as soon as it is possible.
Now, once you’ve setup the ShareActionProvider menu item, construct and attach the share intent for the provider but only after image has been loaded as shown below using the RequestListener for Glide .
Note: Be sure to call attachShareIntentAction method both inside onCreateOptionsMenu AND inside the onResourceReady for Glide to ensure that the share attaches properly.
We can use a similar approach if we wish to create a share action for the current URL that is being loaded in a WebView:
Check out the official guide for easy sharing for more information.
Источник
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 image with link
A simple and customizable full-screen image viewer with shared image transition support, «pinch to zoom» and «swipe to dismiss» gestures. Compatible with all of the most popular image processing libraries such as Picasso , Glide etc. Based on PhotoView by chrisbanes.
Need iOS and Android apps, MVP development or prototyping? Contact us via info@stfalcon.com. We develop software since 2009, and we’re known experts in this field. Check out our portfolio and see more libraries from stfalcon-studio.
- A project configured with the AndroidX
- SDK 19 and and higher
Download via Gradle:
Add this to the project build.gradle file:
And then add the dependency to the module build.gradle file:
Download via Maven:
Where the latest_version is the value from Download badge.
All you need to show the viewer is to pass the context, list or array of your image objects and the implementation of the ImageLoader and call the show() method:
To improve the UX of your app you would like to add a transition when a user opens the viewer. And this is simple as never before! Just tell the viewer which image should be used for animation using withTransitionFrom(myImageView) method and the library will do it for you!
If you need more advanced behavior like updating transition target while changing images in the viewer please see the sample app for how to do this.
Update images list on the fly
There are a lot of common cases (such as pagination, deleting, editing etc.) where you need to update the existing images list while the viewer is running. To do this you can simply update the existing list (or even replace it with a new one) and then call updateImages(images) .
Change current image
Images are not always leafed through by the user. Maybe you want to implement some kind of preview list at the bottom of the viewer — setCurrentPosition is here for help. Change images programmatically wherever you want!
Custom overlay view
If you need to show some content over the image (e.g. sharing or download button, description, numeration etc.) you can set your own custom view using the setOverlayView(customView) and bind it with the viewer through the ImageViewer.OnImageChangeListener .
Use the setBackgroundColorRes(colorRes) or setBackgroundColor(colorInt) to set a color of the fading background.
Simply add margins between images using the withImagesMargin(context, dimenRes) method for dimensions, or use the withImageMarginPixels(int) for pixels size.
Overlay image hides part of the images? Set container padding with dimens using withContainerPadding(context, start, top, end, bottom) or withContainerPadding(context, dimen) for all of the sides evenly. For setting a padding in pixels, just use the withContainerPadding(. ) methods variant.
Status bar visibility
Control the status bar visibility of the opened viewer by using the withHiddenStatusBar(boolean) method ( true by default)
If you need to disable some of the gestures — you can use the allowSwipeToDismiss(boolean) and allowZooming(boolean) methods accordingly.
Here is the example with all of the existing options applied:
Also, you can take a look at the sample project for more information.
Usage with Fresco
If you use the Fresco library — check out the FrescoImageViewer which was also developed by our team.
About
A simple and customizable Android full-screen image viewer with shared image transition support, «pinch to zoom» and «swipe to dismiss» gestures
Источник