Android studio bitmapfactory decoderesource

Полный список

— разбираемся с BitmapFactory.Options
— сохраняем Bitmap в файл

На первом уроке про Bitmap мы обсудили, что для чтения картинки из файла (ресурсов,потока,…) в Bitmap используются decode* методы BitmapFactory. И при чтении мы можем использовать объект BitmapFactory.Options, который позволяет нам задать некоторые параметры. Какие-то из этих параметров весьма специфичны и крайне редко используются, но есть и те, которые могут быть полезны в повседневной работе.

Разберемся, зачем нужны эти параметры, и рассмотрим некоторые из них на примерах.

inJustDecodeBounds

Если включить (true) этот параметр, то система не будет создавать Bitmap, а только вернет информацию о изображение в следующих полях:
outWidth – ширина
outHeight – высота
outMimeType – mimetype

Project name: P1591_BitmapOptions
Build Target: Android 4.4
Application name: BitmapOptions
Package name: ru.startandroid.develop.p1591bitmapoptions
Create Activity: MainActivity

В DrawView указываем inJustDecodeBounds = true, читаем стандартную Android-иконку и выводим в лог информацию о ней.

Запускаем, смотрим лог:

bitmap = null, width = 48, height = 48, mimetype = image/png

У вас ширина и высота могут быть другие, т.к. при чтении картинок из папок res/drawable-*dpi учитывается density устройства.

Bitmap равен null, т.к. система только вернула нам инфу, а Bitmap не создавала, а следовательно и память не занимала.

inSampleSize

Позволяет указать коэффициент уменьшения размера изображения при чтении. Он должен быть кратным 2. Если зададите другое число, то оно будет изменено на ближайшее число меньшее вашего и кратное 2.

Перепишем класс DrawView:

Используем inSampleSize = 2 и в лог выводим размеры, получившегося Bitmap:

width = 24, height = 24

Как и заказывали, картинка при чтении в Bitmap стала в два раза меньше.

Параметры inJustDecodeBounds и inSampleSize можно использовать для чтения больших изображений. Т.е. если вы сразу решите считать большое изображение в Bitmap, вы можете занять, тем самым, слишком много памяти или вообще получить OutOfMemory. Поэтому следует сначала получить данные о размерах картинки, а затем с коэффициентом сжатия считать ее в Bitmap примерно нужного размера. Этот алгоритм мы еще подробно разберем на одном из следующих уроков.

inBitmap

Если передать в этот параметр Bitmap-объект, то он и будет использован для получения результата вместо создания нового Bitmap-объекта.

Тут есть несколько особенностей с версиями Android.

— в Android 4.4 (API 19) передаваемый Bitmap должен быть не меньше по размеру (в байтах), чем читаемое изображение.

— для более ранних версий, передаваемый в inBitmap объект должен быть того же размера (ширина/высота), что и читаемое изображение. Также, в Options необходимо добавлять inSampleSize = 1.

Создаем новый Bitmap-объект tempBitmap и передаем его в inBitmap параметр.

bitmap = android.graphics.Bitmap@5281a428 (48,48), tempBitmap = android.graphics.Bitmap@5281a428

Видно, что bitmap и tempBitmap указывают на один объект. Т.е. decode-метод не создавал новый Bitmap, а прочел изображение в tempBitmap и вернул его, как результат. Размер Bitmap стал 48х48. Хотя изначально мы создавали его размером 300х300.

Если систему что-то не устроит, она может вернуть null или сгенерировать IllegalArgumentException.

Еще раз проговорю, что этот пример сработал на Android 4.4, но на более ранних версиях есть нюансы, которые я чуть выше расписал.

inPreferredConfig

Указание желаемой конфигурации Bitmap.Config.

inDensity

Задает density-значение для Bitmap, аналогично методу setDensity. Для задания значения используйте константы DENSITY* класса DisplayMetrics.

inTargetDensity, inScaled

Если inTargetDensity отличен от inDensity, и inScaled = true (по умолчанию), то размер изображения будет скорректирован от inDensity к inTargetDensity.

inScreenDensity

К сожалению, мне не удалось понять, зачем он нужен. Если есть мысли, пишите на форуме.

inPurgeable

Позволяет системе временно удалить содержимое созданного Bitmap из памяти в случае нехватки таковой. Когда изображение снова понадобится (например при выводе на экран), оно будет восстановлено из источника. Т.е. жертвуем производительностью в пользу памяти.

inInputShareable

Если true, то Bitmap хранит ссылку на источник, иначе – данные источника. Но даже если true, то вполне может быть, что по усмотрению системы будут храниться данные, а не ссылка. Этот параметр актуален только при включенном inPurgeable.

inDither

Попытка сгладить цвета, если текущей цветовой палитры не достаточно для отображения оригинальных цветов изображения

inMutable

Если true, то мы получим mutable Bitmap

inPreferQualityOverSpeed

Включение более качественного декодирования в ущерб скорости

inPremultiplied

Доступен с API Level 19. Дает возможность выключить premultiplied-режим. Если режим включен (по умолчанию), то RGB компоненты в пикселах сразу рассчитаны с учетом альфа-компонента (для лучшей производительности). Канва принимает Bitmap только в таком режиме. В хелпе сказано, что выключение режима может понадобиться для специфических задач: RenderScript и OpenGL.

inTempStorage

Здесь можем указать свой временный массив, который будет использован в процессе декодирования

mCancel

По этой метке можно определить был ли процесс декодирования отменен методом requestCancelDecode

Как сохранить Bitmap в файл

Метод compress позволяет сохранить Bitmap в разных форматах в исходящий поток. На вход принимает:
— формат (JPG, PNG, WEBP)
— качество сжатия, от 0 (наихудшее) до 100 (наилучшее)
— поток

Рассмотрим пример, в котором создадим Bitmap, нарисуем на нем что-нибудь и сохраним на SD.

В bmpIcon читаем стандартную иконку, затем меняем размер на 500х500. Создаем новый bitmap, заполняем его белым, рисуем в нем bmpIcon и пишем текст.

Далее создаем объект File, который указывает на файл savedBitmap.png в стандартной папке Pictures. Для этого файла создаем поток FileOutputStream, который передаем в метод compress. Также в методе указываем формат JPEG и качество = 100.

После запуска приложения идем в папку Pictures, там должен быть файл savedBitmap.png.

На следующем уроке:

— читаем и отображаем большие изображения

Присоединяйтесь к нам в Telegram:

— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование

Читайте также:  Samsung galaxy s4 mini характеристики андроид

— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня

— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме

Источник

Класс BitmapFactory

Класс BitmapFactory позволяет создать объект Bitmap из файла, потока или байтового массива. Данный класс часто используется в работе с изображениями.

Класс имеет несколько методов decode* (decodeByteArray(), decodeFile(), decodeResource() и др.) для создания растрового изображения из различных источников. Не забывайте, что методы пытаются выделить память под создаваемое изображение и вы можете получить ошибку из-за нехватки памяти на устройстве. Обратите внимание, что каждый метод имеет вторую перегруженную версию с тем же именем и дополнительным параметром типа BitmapFactory.Options.

Мы можем загрузить изображение из каталога assets:

Класс BitmapFactory.Options имеет несколько полезных свойств, которые нужно использовать в своих приложениях.

  • inJustDecodeBounds
  • inSampleSize
  • inBitmap
  • inPreferredConfig
  • inDensity
  • inDither
  • inPurgeable

inJustDecodeBounds

Используя свойство inJustDecodeBounds со значением true, вы можете избежать выделения памяти под изображение, при этом вы можете получить значения ширины (outWidth), высоты (outHeight) и MIME-типа (outMimeType). Подобный приём позволяет прочитать размеры картинки и использовать их для своих целей, сведя к минимуму потребление памяти.

Когда размеры изображения известны, вы уже можете решать — загружать ли полное изображение или сделать уменьшенную копию. Тут зависит от логики вашего приложения. Если это просмотр фотографий, то нужно следить за потреблением памяти. Если картинка загружается в маленький ImageView, то нет смысла использовать настоящее большое изображение. Когда вы определились, что делать дальше, то установите снова значение false для данного свойства.

inSampleSize

Чтобы декодер пережал картинку, установите inSampleSize в нужное значение в объекте BitmapFactory.Options. Например, если изображение с размерами 2048×1536 сжать до размеров 512×384 (в 4 раза), то изображение в памяти будет занимать 0.75мб вместо 12мб. Разница ощутима.

Ниже приводится метод для вычисления новых размеров изображения по заданными ширине и высоте, чтобы изменение размера было пропорциональным.

Чтобы использовать этот метод, сначала декодируйте изображение через inJustDecodeBounds = true, затем декодируйте снова, используя новые значения inSampleSize и inJustDecodeBounds = false:

Чтобы загрузить большое изображение в ImageView с размером 100х100 пикселей, используйте наш метод:

По такому же принципу вы можете написать сопутствующие методы для других декодирующих методов класса BitmapFactory.

Сама операция сжатия картинки очень трудоёмка и её не стоит делать в основном потоке приложения. Лучше её вынести в отдельный поток через AsyncTask.

Другие свойства используются реже. Поэтому информация только в ознакомительных целях.

inBitmap

Если передать в этот параметр объект Bitmap, то он и будет использован для получения итогового результата вместо создания нового объекта. В Android 4.4 (API 19) передаваемый Bitmap должен быть не меньше по размеру (в байтах), чем читаемое изображение. В старых версиях объект должен быть строго того же размера (ширина/высота), что и читаемое изображение. Также необходимо использовать свойство inSampleSize = 1.

inPreferredConfig

inDensity

Задаёт плотность для объекта Bitmap.

inDither

Сглаживание цветовой палитры. Где-то валялся пример. Если найду, то добавлю.

inPurgeable

При проблемах с памятью разрешаем системе временно удалить объект Bitmap. Когда потребуется вывести картинку на экран, то объект восстанавливается. Естественно, при этом падает производительность из-за повторной работы по обработке изображения.

Об остальных свойствах читайте в документации.

Источник

Bitmap Factory. Decode Resource Method

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Overloads

Synonym for #decodeResource(Resources, int, android.graphics.BitmapFactory.Options) with null Options.

Synonym for #decodeResource(Resources, int, android.graphics.BitmapFactory.Options) with null Options.

DecodeResource(Resources, Int32)

Synonym for #decodeResource(Resources, int, android.graphics.BitmapFactory.Options) with null Options.

Parameters

The resources object containing the image data

The resource id of the image data

Returns

The decoded bitmap, or null if the image could not be decoded.

Remarks

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Applies to

DecodeResource(Resources, Int32, BitmapFactory+Options)

Synonym for #decodeResource(Resources, int, android.graphics.BitmapFactory.Options) with null Options.

Parameters

The resources object containing the image data

The resource id of the image data

null-ok; Options that control downsampling and whether the image should be completely decoded, or just is size returned.

Returns

The decoded bitmap, or null if the image could not be decoded.

Remarks

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Источник

BitmapFactory.Options

java.lang.Object
android.graphics.BitmapFactory.Options

Summary

Fields
inBitmap If set, decode methods that take the Options object will attempt to reuse this bitmap when loading content.
inDensity The pixel density to use for the bitmap.
inDither If dither is true, the decoder will attempt to dither the decoded image.
inInputShareable This field was deprecated in API level 21. As of LOLLIPOP , this is ignored. In KITKAT and below, this field works in conjuction with inPurgeable. If inPurgeable is false, then this field is ignored. If inPurgeable is true, then this field determines whether the bitmap can share a reference to the input data (inputstream, array, etc.) or if it must make a deep copy.
inJustDecodeBounds If set to true, the decoder will return null (no bitmap), but the out.
inMutable If set, decode methods will always return a mutable Bitmap instead of an immutable one.
inPreferQualityOverSpeed If inPreferQualityOverSpeed is set to true, the decoder will try to decode the reconstructed image to a higher quality even at the expense of the decoding speed.
inPreferredConfig If this is non-null, the decoder will try to decode into this internal configuration.
inPremultiplied If true (which is the default), the resulting bitmap will have its color channels pre-multipled by the alpha channel.
inPurgeable This field was deprecated in API level 21. As of LOLLIPOP , this is ignored. In KITKAT and below, if this is set to true, then the resulting bitmap will allocate its pixels such that they can be purged if the system needs to reclaim memory. In that instance, when the pixels need to be accessed again (e.g. the bitmap is drawn, getPixels() is called), they will be automatically re-decoded.

For the re-decode to happen, the bitmap must have access to the encoded data, either by sharing a reference to the input or by making a copy of it. This distinction is controlled by inInputShareable. If this is true, then the bitmap may keep a shallow reference to the input. If this is false, then the bitmap will explicitly make a copy of the input data, and keep that. Even if sharing is allowed, the implementation may still decide to make a deep copy of the input data.

While inPurgeable can help avoid big Dalvik heap allocations (from API level 11 onward), it sacrifices performance predictability since any image that the view system tries to draw may incur a decode delay which can lead to dropped frames. Therefore, most apps should avoid using inPurgeable to allow for a fast and fluid UI. To minimize Dalvik heap allocations use the inBitmap flag instead.

inSampleSize If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. inScaled When this flag is set, if inDensity and inTargetDensity are not 0, the bitmap will be scaled to match inTargetDensity when loaded, rather than relying on the graphics system scaling it each time it is drawn to a Canvas. inScreenDensity The pixel density of the actual screen that is being used. inTargetDensity The pixel density of the destination this bitmap will be drawn to. inTempStorage Temp storage to use for decoding. mCancel Flag to indicate that cancel has been called on this object. outHeight The resulting height of the bitmap. outMimeType If known, this string is set to the mimetype of the decoded image. outWidth The resulting width of the bitmap.

Fields

public Bitmap inBitmap

If set, decode methods that take the Options object will attempt to reuse this bitmap when loading content. If the decode operation cannot use this bitmap, the decode method will return null and will throw an IllegalArgumentException. The current implementation necessitates that the reused bitmap be mutable, and the resulting reused bitmap will continue to remain mutable even when decoding a resource which would normally result in an immutable bitmap.

You should still always use the returned Bitmap of the decode method and not assume that reusing the bitmap worked, due to the constraints outlined above and failure situations that can occur. Checking whether the return value matches the value of the inBitmap set in the Options structure will indicate if the bitmap was reused, but in all cases you should use the Bitmap returned by the decoding function to ensure that you are using the bitmap that was used as the decode destination.

Usage with BitmapFactory

As of KITKAT , any mutable bitmap can be reused by BitmapFactory to decode any other bitmaps as long as the resulting byte count of the decoded bitmap is less than or equal to the allocated byte count of the reused bitmap. This can be because the intrinsic size is smaller, or its size post scaling (for density / sample size) is smaller.

Prior to KITKAT additional constraints apply: The image being decoded (whether as a resource or as a stream) must be in jpeg or png format. Only equal sized bitmaps are supported, with inSampleSize set to 1. Additionally, the configuration of the reused bitmap will override the setting of inPreferredConfig , if set.

Usage with BitmapRegionDecoder

BitmapRegionDecoder will draw its requested content into the Bitmap provided, clipping if the output content size (post scaling) is larger than the provided Bitmap. The provided Bitmap’s width, height, and Bitmap.Config will not be changed.

BitmapRegionDecoder support for inBitmap was introduced in JELLY_BEAN . All formats supported by BitmapRegionDecoder support Bitmap reuse via inBitmap .

See Also

public int inDensity

The pixel density to use for the bitmap. This will always result in the returned bitmap having a density set for it (see Bitmap.setDensity(int) ). In addition, if inScaled is set (which it is by default> and this density does not match inTargetDensity , then the bitmap will be scaled to the target density before being returned.

See Also

public boolean inDither

If dither is true, the decoder will attempt to dither the decoded image.

public boolean inInputShareable

This field was deprecated in API level 21.
As of LOLLIPOP , this is ignored. In KITKAT and below, this field works in conjuction with inPurgeable. If inPurgeable is false, then this field is ignored. If inPurgeable is true, then this field determines whether the bitmap can share a reference to the input data (inputstream, array, etc.) or if it must make a deep copy.

public boolean inJustDecodeBounds

If set to true, the decoder will return null (no bitmap), but the out. fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.

public boolean inMutable

If set, decode methods will always return a mutable Bitmap instead of an immutable one. This can be used for instance to programmatically apply effects to a Bitmap loaded through BitmapFactory.

public boolean inPreferQualityOverSpeed

If inPreferQualityOverSpeed is set to true, the decoder will try to decode the reconstructed image to a higher quality even at the expense of the decoding speed. Currently the field only affects JPEG decode, in the case of which a more accurate, but slightly slower, IDCT method will be used instead.

public Bitmap.Config inPreferredConfig

If this is non-null, the decoder will try to decode into this internal configuration. If it is null, or the request cannot be met, the decoder will try to pick the best matching config based on the system’s screen depth, and characteristics of the original image such as if it has per-pixel alpha (requiring a config that also does). Image are loaded with the ARGB_8888 config by default.

public boolean inPremultiplied

If true (which is the default), the resulting bitmap will have its color channels pre-multipled by the alpha channel.

This should NOT be set to false for images to be directly drawn by the view system or through a Canvas . The view system and Canvas assume all drawn images are pre-multiplied to simplify draw-time blending, and will throw a RuntimeException when un-premultiplied are drawn.

This is likely only useful if you want to manipulate raw encoded image data, e.g. with RenderScript or custom OpenGL.

This does not affect bitmaps without an alpha channel.

Setting this flag to false while setting inScaled to true may result in incorrect colors.

See Also

public boolean inPurgeable

This field was deprecated in API level 21.
As of LOLLIPOP , this is ignored. In KITKAT and below, if this is set to true, then the resulting bitmap will allocate its pixels such that they can be purged if the system needs to reclaim memory. In that instance, when the pixels need to be accessed again (e.g. the bitmap is drawn, getPixels() is called), they will be automatically re-decoded.

For the re-decode to happen, the bitmap must have access to the encoded data, either by sharing a reference to the input or by making a copy of it. This distinction is controlled by inInputShareable. If this is true, then the bitmap may keep a shallow reference to the input. If this is false, then the bitmap will explicitly make a copy of the input data, and keep that. Even if sharing is allowed, the implementation may still decide to make a deep copy of the input data.

While inPurgeable can help avoid big Dalvik heap allocations (from API level 11 onward), it sacrifices performance predictability since any image that the view system tries to draw may incur a decode delay which can lead to dropped frames. Therefore, most apps should avoid using inPurgeable to allow for a fast and fluid UI. To minimize Dalvik heap allocations use the inBitmap flag instead.

public int inSampleSize

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value public boolean inScaled

When this flag is set, if inDensity and inTargetDensity are not 0, the bitmap will be scaled to match inTargetDensity when loaded, rather than relying on the graphics system scaling it each time it is drawn to a Canvas.

BitmapRegionDecoder ignores this flag, and will not scale output based on density. (though inSampleSize is supported)

This flag is turned on by default and should be turned off if you need a non-scaled version of the bitmap. Nine-patch bitmaps ignore this flag and are always scaled.

If inPremultiplied is set to false, and the image has alpha, setting this flag to true may result in incorrect colors.

public int inScreenDensity

The pixel density of the actual screen that is being used. This is purely for applications running in density compatibility code, where inTargetDensity is actually the density the application sees rather than the real screen density.

By setting this, you allow the loading code to avoid scaling a bitmap that is currently in the screen density up/down to the compatibility density. Instead, if inDensity is the same as inScreenDensity , the bitmap will be left as-is. Anything using the resulting bitmap must also used Bitmap.getScaledWidth and Bitmap.getScaledHeight to account for any different between the bitmap’s density and the target’s density.

This is never set automatically for the caller by BitmapFactory itself. It must be explicitly set, since the caller must deal with the resulting bitmap in a density-aware way.

See Also

public int inTargetDensity

The pixel density of the destination this bitmap will be drawn to. This is used in conjunction with inDensity and inScaled to determine if and how to scale the bitmap before returning it.

If this is 0, decodeResource(Resources, int) , decodeResource(Resources, int, android.graphics.BitmapFactory.Options) , and decodeResourceStream(Resources, TypedValue, InputStream, Rect, BitmapFactory.Options) will fill in the density associated the Resources object’s DisplayMetrics. The other functions will leave it as-is and no scaling for density will be performed.

See Also

public byte[] inTempStorage

Temp storage to use for decoding. Suggest 16K or so.

public boolean mCancel

Flag to indicate that cancel has been called on this object. This is useful if there’s an intermediary that wants to first decode the bounds and then decode the image. In that case the intermediary can check, inbetween the bounds decode and the image decode, to see if the operation is canceled.

public int outHeight

The resulting height of the bitmap. If inJustDecodeBounds is set to false, this will be height of the output bitmap after any scaling is applied. If true, it will be the height of the input image without any accounting for scaling.

outHeight will be set to -1 if there is an error trying to decode.

public String outMimeType

If known, this string is set to the mimetype of the decoded image. If not know, or there is an error, it is set to null.

public int outWidth

The resulting width of the bitmap. If inJustDecodeBounds is set to false, this will be width of the output bitmap after any scaling is applied. If true, it will be the width of the input image without any accounting for scaling.

outWidth will be set to -1 if there is an error trying to decode.

Public Constructors

public BitmapFactory.Options ()

Create a default Options object, which if left unchanged will give the same result from the decoder as if null were passed.

Public Methods

public void requestCancelDecode ()

This can be called from another thread while this options object is inside a decode. call. Calling this will notify the decoder that it should cancel its operation. This is not guaranteed to cancel the decode, but if it does, the decoder. operation will return null, or if inJustDecodeBounds is true, will set outWidth/outHeight to -1

Источник

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