Android bitmap from byte array

Содержание
  1. Класс Bitmap
  2. Bitmap.Config
  3. Получить Bitmap из ImageView
  4. Изменение размеров — метод createScaledBitmap()
  5. Кадрирование — метод createBitmap()
  6. Меняем цвета каждого пикселя
  7. Конвертируем Bitmap в байтовый массив и обратно
  8. Сжимаем картинку
  9. Как раскодировать Bitmap из Base64
  10. Вычисляем средние значения цветов
  11. Дополнительные материалы
  12. [ Android Newbie ]
  13. Convert Bitmap to byte array and reverse
  14. Pete’s Sharing
  15. Like this:
  16. Related
  17. Bitmap
  18. Summary
  19. Constants
  20. public static final int DENSITY_NONE
  21. Fields
  22. public static final Creator CREATOR
  23. Public Methods
  24. public boolean compress (Bitmap.CompressFormat format, int quality, OutputStream stream)
  25. public Bitmap copy (Bitmap.Config config, boolean isMutable)
  26. public void copyPixelsFromBuffer (Buffer src)
  27. public void copyPixelsToBuffer (Buffer dst)
  28. public static Bitmap createBitmap (DisplayMetrics display, int[] colors, int width, int height, Bitmap.Config config)
  29. public static Bitmap createBitmap (DisplayMetrics display, int width, int height, Bitmap.Config config)
  30. public void eraseColor (int c)
  31. public Bitmap extractAlpha ()
  32. public Bitmap extractAlpha (Paint paint, int[] offsetXY)
  33. public final int getAllocationByteCount ()
  34. public final int getByteCount ()
  35. public final Bitmap.Config getConfig ()
  36. public int getDensity ()
  37. public int getGenerationId ()
  38. public final int getHeight ()
  39. public byte[] getNinePatchChunk ()
  40. public int getPixel (int x, int y)
  41. public void getPixels (int[] pixels, int offset, int stride, int x, int y, int width, int height)
  42. public int getScaledHeight (DisplayMetrics metrics)
  43. public int getScaledHeight (int targetDensity)
  44. public int getScaledHeight (Canvas canvas)
  45. public int getScaledWidth (int targetDensity)
  46. public int getScaledWidth (DisplayMetrics metrics)
  47. public int getScaledWidth (Canvas canvas)
  48. public final int getWidth ()
  49. public final boolean hasAlpha ()
  50. public final boolean hasMipMap ()
  51. public final boolean isMutable ()
  52. public final boolean isPremultiplied ()
  53. public final boolean isRecycled ()
  54. public void prepareToDraw ()
  55. public void reconfigure (int width, int height, Bitmap.Config config)
  56. public void recycle ()
  57. public boolean sameAs (Bitmap other)
  58. public void setConfig (Bitmap.Config config)
  59. public void setDensity (int density)
  60. public void setHasAlpha (boolean hasAlpha)
  61. public final void setHasMipMap (boolean hasMipMap)

Класс Bitmap

Вам часто придётся иметь дело с изображениями котов, которые хранятся в файлах JPG, PNG, GIF. По сути, любое изображение, которое мы загружаем из графического файла, является набором цветных точек (пикселей). А информацию о каждой точке можно сохранить в битах. Отсюда и название — карта битов или по-буржуйски — bitmap. У нас иногда используется термин растр или растровое изображение. В Android есть специальный класс android.graphics.Bitmap для работы с подобными картинками.

Существуют готовые растровые изображения в файлах, о которых поговорим ниже. А чтобы создать с нуля объект Bitmap программным способом, нужно вызвать метод createBitmap():

В результате получится прямоугольник с заданными размерами в пикселях (первые два параметра). Третий параметр отвечает за информацию о прозрачности и качестве цвета (в конце статьи есть примеры).

Очень часто нужно знать размеры изображения. Чтобы узнать его ширину и высоту в пикселах, используйте соответствующие методы:

Bitmap.Config

Кроме размеров, желательно знать цветовую схему. У класса Bitmap есть метод getConfig(), который возвращает перечисление Bitmap.Config.

Всего существует несколько элементов перечисления.

  • Bitmap.Config ALPHA_8 — каждый пиксель содержит в себе информацию только о прозрачности, о цвете здесь ничего нет. Каждый пиксель требует 8 бит (1 байт) памяти.
  • Bitmap.Config ARGB_4444 — устаревшая конфигурация, начиная с API 13. Аналог ARGB_8888, только каждому ARGB-компоненту отведено не по 8, а по 4 бита. Соответственно пиксель весит 16 бит (2 байта). Рекомендуется использовать ARGB_8888
  • Bitmap.Config ARGB_8888 — на каждый из 4-х ARGB-компонентов пикселя (альфа, красный, зеленый, голубой) выделяется по 8 бит (1 байт). Каждый пиксель занимает 4 байта. Обладает наивысшим качеством для картинки.
  • Bitmap.Config RGB_565 — красному и и синему компоненту выделено по 5 бит (32 различных значений), а зелёному — шесть бит (64 возможных значений). Картинка с такой конфигурацией может иметь артефакты. Каждый пиксель будет занимать 16 бит или 2 байта. Конфигурация не хранит информацию о прозрачности. Можно использовать в тех случаях, когда рисунки не требуют прозрачности и высокого качества.

Конфигурация RGB_565 была очень популярна на старых устройствах. С увеличением памяти и мощности процессоров данная конфигурация теряет актуальность.

В большинстве случаев вы можете использовать ARGB_8888.

Получив объект в своё распоряжение, вы можете управлять каждой его точкой. Например, закрасить его синим цветом.

Чтобы закрасить отдельную точку, используйте метод setPixel() (парный ему метод getPixel позволит узнать информацию о точке). Закрасим красной точкой центр синего прямоугольника из предыдущего примера — имитация следа от лазерной указки. Котам понравится.

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

Созданный нами цветной прямоугольник и управление отдельными точками не позволят вам нарисовать фигуру, не говоря уже о полноценном рисунке. Класс Bitmap не имеет своих методов для рисования, для этого есть метод Canvas (Холст), на котором вы можете размещать объекты Bitmap.

Когда вы размещали в разметке активности компонент ImageView и присваивали атрибуту android:src ресурс из папок drawable-xxx, то система автоматически выводила изображение на экран.

Если нужно программно получить доступ к битовой карте (изображению) из ресурса, то используется такой код:

Обратный процес конвертации из Bitmap в Drawable:

Изображение можно сохранить, например, на SD-карту в виде файла (кусок кода):

Каждая точка изображения представлена в виде 4-байтного целого числа. Сначала идёт байт прозрачности — значение 0 соответствует полной прозрачности, а 255 говорит о полной непрозрачности. Промежуточные значения позволяют делать полупрозрачные изображения. Этим искусством в совершенстве владел чеширский кот, который умело управлял всеми точками своего тела и растворялся в пространстве, только улыбка кота долго ещё висела в воздухе (что-то я отвлёкся).

Следующие три байта отвечают за красный, зелёный и синий цвет, которые работают по такому же принципу. Т.е. значение 255 соответствует насыщенному красному цвету и т.д.

Так как любое изображение кота — это набор точек, то с помощью метода getPixels() мы можем получить массив этих точек, сделать с этой точкой что-нибудь нехорошее (поменять прозрачность или цвет), а потом с помощью родственного метода setPixels() записать новые данные обратно в изображение. Так можно перекрасить чёрного кота в белого и наоборот. Если вам нужна конкретная точка на изображении, то используйте методы getPixel()/setPixel(). Подобный подход используется во многих графических фильтрах. Учтите, что операция по замене каждой точки в большом изображении занимает много времени. Желательно проводить подобные операции в отдельном потоке.

На этом базовая часть знакомства с битовой картой закончена. Теперь подробнее.

Учитывая ограниченные возможности памяти у мобильных устройств, следует быть осторожным при использовании объекта Bitmap во избежание утечки памяти. Не забывайте освобождать ресурсы при помощи метода recycle(), если вы в них не нуждаетесь. Например:

Почему это важно? Если не задумываться о ресурсах памяти, то можете получить ошибку OutOfMemoryError. На каждое приложение выделяется ограниченное количество памяти (heap size), разное в зависимости от устройства. Например, 16мб, 24мб и выше. Современные устройства как правило имеют 24мб и выше, однако это не так много, если ваше приложение злоупотребляет графическими файлами.

Bitmap на каждый пиксель тратит в общем случае 2 или 4 байта (зависит от битности изображения – 16 бит RGB_555 или 32 бита ARGB_888). Можно посчитать, сколько тратится ресурсов на Bitmap, содержащий изображение, снятое на 5-мегапиксельную камеру.

При соотношении сторон 4:3 получится изображение со сторонами 2583 х 1936. В конфигурации RGB_555 объект Bitmap займёт 2592 * 1936 * 2 = около 10Мб, а в ARGB_888 (режим по умолчанию) в 2 раза больше – чуть более 19Мб.

Во избежание проблем с памятью прибегают к помощи методов decodeXXX() класса BitmapFactory.

Если установить атрибут largeHeap в манифесте, то приложению будет выделен дополнительный блок памяти.

Ещё одна потенциальная проблема. У вас есть Bitmap и присвоили данный объект кому-то. Затем объект был удалён из памяти, а ссылка на него осталась. Получите крах приложения с ошибкой типа «Exception on Bitmap, throwIfRecycled».

Возможно, лучше сделать копию.

Получить Bitmap из ImageView

Если в ImageView имеется изображение, то получить Bitmap можно следующим образом:

Но с этим способом нужно быть осторожным. Например, если в ImageView используются элементы LayerDrawable, то возникнет ошибка. Можно попробовать такой вариант.

Более сложный вариант, но и более надёжный.

Изменение размеров — метод createScaledBitmap()

С помощью метода createScaledBitmap() можно изменить размер изображения.

Будем тренироваться на кошках. Добавим картинку в ресурсы (res/drawable). В разметку добавим два элемента ImageView

В последнем параметре у метода идёт булева переменная, отвечающая за сглаживание пикселей. Обычно его применяют, когда маленькое изображение увеличивают в размерах, чтобы улучшить качество картинки. При уменьшении, как правило, в этом нет такой необходимости.

Кадрирование — метод createBitmap()

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

  • сreateBitmap(Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter) — Returns an immutable bitmap from subset of the source bitmap, transformed by the optional matrix.
  • createBitmap(int width, int height, Bitmap.Config config) — Returns a mutable bitmap with the specified width and height.
  • createBitmap(Bitmap source, int x, int y, int width, int height) — Returns an immutable bitmap from the specified subset of the source bitmap.
  • createBitmap(int[] colors, int offset, int stride, int width, int height, Bitmap.Config config) — Returns a immutable bitmap with the specified width and height, with each pixel value set to the corresponding value in the colors array.
  • createBitmap(Bitmap src) — Returns an immutable bitmap from the source bitmap.
  • createBitmap(int[] colors, int width, int height, Bitmap.Config config) — Returns a immutable bitmap with the specified width and height, with each pixel value set to the corresponding value in the colors array.
Читайте также:  Создание живых обоев для android

Описываемый ниже код не является оптимальным и очень ресурсоёмкий. На больших изображениях код будет сильно тормозить. Приводится для ознакомления. Чтобы вывести часть картинки, можно сначала создать нужный Bitmap с заданными размерами, занести в массив каждый пиксель исходного изображения, а затем этот же массив вернуть обратно. Но, так как мы уже задали другие размеры, то часть пикселей не выведутся.

По аналогии мы можем вывести и нижнюю правую часть изображения:

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

Скриншот приводить не буду, проверьте самостоятельно.

Меняем цвета каждого пикселя

Через метод getPixels() мы можем получить массив всех пикселей растра, а затем в цикле заменить определённым образом цвета в пикселе и получить перекрашенную картинку. Для примера возьмем стандартный значок приложения, поместим его в ImageView, извлечём информацию из значка при помощи метода decodeResource(), применим собственные методы замены цвета и полученный результат поместим в другие ImageView:

Код для класса активности:

На скриншоте представлен оригинальный значок и три варианта замены цветов.

Ещё один пример, где также в цикле меняем цвет каждого пикселя Green->Blue, Red->Green, Blue->Red (добавьте на экран два ImageView):

Конвертируем Bitmap в байтовый массив и обратно

Сжимаем картинку

В предыдущем примере вызывался метод compress(). Несколько слов о нём. В первом аргументе передаём формат изображения, поддерживаются форматы JPEG, PNG, WEBP. Во втором аргументе указываем степень сжатия от 0 до 100, 0 — для получения малого размера файла, 100 — максимальное качество. Формат PNG не поддерживает сжатие с потерей качества и будет игнорировать данное значение. В третьем аргументе указываем файловый поток.

Как раскодировать Bitmap из Base64

Если изображение передаётся в текстовом виде через Base64-строку, то воспользуйтесь методом, позволяющим получить картинку из этой строки:

Вычисляем средние значения цветов

Дополнительные материалы

На StackOverFlow есть интересный пример программной генерации цветных квадратов с первой буквой слова. В пример квадрат используется как значок к приложению. Также популярен этот приём в списках. Квадраты также заменять кружочками.

Источник

[ Android Newbie ]

Convert Bitmap to byte array and reverse

If you want to convert a ` Bitmap ` to byte array:

and if you want the reverse process:

Pete’s Sharing

Like this:

Merci beaucoup le gar, thx.

I want to send image from android to matlab. In this i firstly converted that image into bitmap and convert into bytearray.i not know how to send byte array or can i send pixels array.plz help

hey i need to convert a bytebuffer to bitmap.here is code

byte[] bytes = new byte[10];
byte_buffer = ByteBuffer.wrap(bytes);
bytes = new byte[byte_buffer.remaining()];
byte_buffer.get(bytes, 0, bytes.length);
byte_buffer.clear();
bytes = new byte[byte_buffer.capacity()];
byte_buffer.get(bytes, 0, bytes.length);
Bitmap sb = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

Error log:
— SkImageDecode : Factory returned null;

This is really interesting, You’re a very skilled blogger.
I’ve joined your feed and look forward to seeking more of
your wonderful post. Also, I have shared your web site in my social networks!

Hi there, I discovered your site by the use of Google
even as searching for a similar topic, your website came up, it seems
good. I have bookmarked it in my google bookmarks.

Hi there, simply changed into alert to your blog
thru Google, and found that it’s really informative.
I am going to be careful for brussels. I’ll be grateful for those who continue this in future.
A lot of folks might be benefited from your writing. Cheers!

Источник

Bitmap

Summary

Nested Classes
Bitmap.CompressFormat Specifies the known formats a bitmap can be compressed into
Bitmap.Config Possible bitmap configurations.
Constants
int DENSITY_NONE Indicates that the bitmap was created for an unknown pixel density.
[Expand]
int CONTENTS_FILE_DESCRIPTOR Bit masks for use with describeContents() : each bit represents a kind of object considered to have potential special significance when marshalled.
int PARCELABLE_WRITE_RETURN_VALUE Flag for use with writeToParcel(Parcel, int) : the object being written is a return value, that is the result of a function such as » Parcelable someFunction() «, » void someFunction(out Parcelable) «, or » void someFunction(inout Parcelable) «.

Copy the pixels from the buffer, beginning at the current position, overwriting the bitmap’s pixels.

Copy the bitmap’s pixels into the specified buffer (allocated by the caller).

Returns the density for this bitmap.

Indicates whether pixels stored in this bitmaps are stored pre-multiplied.

Modifies the bitmap to have a specified width, height, and Bitmap.Config , without affecting the underlying allocation backing the bitmap.

Convenience method for calling reconfigure(int, int, Config) with the current height and width.

Specifies the density for this bitmap.

Convenience method for calling reconfigure(int, int, Config) with the current width and config.

Write the specified Color into the bitmap (assuming it is mutable) at the x,y coordinate.

Replace pixels in the bitmap with the colors in the array.

Convenience method for calling reconfigure(int, int, Config) with the current height and config.

Constants

public static final int DENSITY_NONE

Indicates that the bitmap was created for an unknown pixel density.

See Also

Fields

public static final Creator CREATOR

Public Methods

public boolean compress (Bitmap.CompressFormat format, int quality, OutputStream stream)

Write a compressed version of the bitmap to the specified outputstream. If this returns true, the bitmap can be reconstructed by passing a corresponding inputstream to BitmapFactory.decodeStream(). Note: not all Formats support all bitmap configs directly, so it is possible that the returned bitmap from BitmapFactory could be in a different bitdepth, and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque pixels).

Parameters
format The format of the compressed image
quality Hint to the compressor, 0-100. 0 meaning compress for small size, 100 meaning compress for max quality. Some formats, like PNG which is lossless, will ignore the quality setting
stream The outputstream to write the compressed data.
Returns
  • true if successfully compressed to the specified stream.

public Bitmap copy (Bitmap.Config config, boolean isMutable)

Tries to make a new bitmap based on the dimensions of this bitmap, setting the new bitmap’s config to the one specified, and then copying this bitmap’s pixels into the new bitmap. If the conversion is not supported, or the allocator fails, then this returns NULL. The returned bitmap initially has the same density as the original.

Parameters
config The desired config for the resulting bitmap
isMutable True if the resulting bitmap should be mutable (i.e. its pixels can be modified)
Returns
  • the new bitmap, or null if the copy could not be made.

public void copyPixelsFromBuffer (Buffer src)

Copy the pixels from the buffer, beginning at the current position, overwriting the bitmap’s pixels. The data in the buffer is not changed in any way (unlike setPixels(), which converts from unpremultipled 32bit to whatever the bitmap’s native format is.

After this method returns, the current position of the buffer is updated: the position is incremented by the number of elements read from the buffer. If you need to read the bitmap from the buffer again you must first rewind the buffer.

public void copyPixelsToBuffer (Buffer dst)

Copy the bitmap’s pixels into the specified buffer (allocated by the caller). An exception is thrown if the buffer is not large enough to hold all of the pixels (taking into account the number of bytes per pixel) or if the Buffer subclass is not one of the support types (ByteBuffer, ShortBuffer, IntBuffer).

The content of the bitmap is copied into the buffer as-is. This means that if this bitmap stores its pixels pre-multiplied (see isPremultiplied() , the values in the buffer will also be pre-multiplied.

After this method returns, the current position of the buffer is updated: the position is incremented by the number of elements written in the buffer.

public static Bitmap createBitmap (DisplayMetrics display, int[] colors, int width, int height, Bitmap.Config config)

Returns a immutable bitmap with the specified width and height, with each pixel value set to the corresponding value in the colors array. Its initial density is determined from the given DisplayMetrics .

Parameters
display Display metrics for the display this bitmap will be drawn on.
colors Array of Color used to initialize the pixels. This array must be at least as large as width * height.
width The width of the bitmap
height The height of the bitmap
config The bitmap config to create. If the config does not support per-pixel alpha (e.g. RGB_565), then the alpha bytes in the colors[] will be ignored (assumed to be FF)
Throws
IllegalArgumentException if the width or height are public static Bitmap createBitmap (DisplayMetrics display, int[] colors, int offset, int stride, int width, int height, Bitmap.Config config)

Returns a immutable bitmap with the specified width and height, with each pixel value set to the corresponding value in the colors array. Its initial density is determined from the given DisplayMetrics .

Parameters
display Display metrics for the display this bitmap will be drawn on.
colors Array of Color used to initialize the pixels.
offset Number of values to skip before the first color in the array of colors.
stride Number of colors in the array between rows (must be >= width or public static Bitmap createBitmap (Bitmap source, int x, int y, int width, int height)

Returns an immutable bitmap from the specified subset of the source bitmap. The new bitmap may be the same object as source, or a copy may have been made. It is initialized with the same density as the original bitmap.

Parameters
source The bitmap we are subsetting
x The x coordinate of the first pixel in source
y The y coordinate of the first pixel in source
width The number of pixels in each row
height The number of rows
Returns
  • A copy of a subset of the source bitmap or the source bitmap itself.
Throws
IllegalArgumentException if the x, y, width, height values are outside of the dimensions of the source bitmap, or width is public static Bitmap createBitmap (Bitmap src)

Returns an immutable bitmap from the source bitmap. The new bitmap may be the same object as source, or a copy may have been made. It is initialized with the same density as the original bitmap.

public static Bitmap createBitmap (DisplayMetrics display, int width, int height, Bitmap.Config config)

Returns a mutable bitmap with the specified width and height. Its initial density is determined from the given DisplayMetrics .

Parameters
display Display metrics for the display this bitmap will be drawn on.
width The width of the bitmap
height The height of the bitmap
config The bitmap config to create.
Throws
IllegalArgumentException if the width or height are public static Bitmap createBitmap (Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter)

Returns an immutable bitmap from subset of the source bitmap, transformed by the optional matrix. The new bitmap may be the same object as source, or a copy may have been made. It is initialized with the same density as the original bitmap. If the source bitmap is immutable and the requested subset is the same as the source bitmap itself, then the source bitmap is returned and no new bitmap is created.

Parameters
source The bitmap we are subsetting
x The x coordinate of the first pixel in source
y The y coordinate of the first pixel in source
width The number of pixels in each row
height The number of rows
m Optional matrix to be applied to the pixels
filter true if the source should be filtered. Only applies if the matrix contains more than just translation.
Returns
  • A bitmap that represents the specified subset of source
Throws
IllegalArgumentException if the x, y, width, height values are outside of the dimensions of the source bitmap, or width is public static Bitmap createBitmap (int width, int height, Bitmap.Config config)

Returns a mutable bitmap with the specified width and height. Its initial density is as per getDensity() .

Parameters
width The width of the bitmap
height The height of the bitmap
config The bitmap config to create.
Throws
IllegalArgumentException if the width or height are public static Bitmap createBitmap (int[] colors, int offset, int stride, int width, int height, Bitmap.Config config)

Returns a immutable bitmap with the specified width and height, with each pixel value set to the corresponding value in the colors array. Its initial density is as per getDensity() .

Parameters
colors Array of Color used to initialize the pixels.
offset Number of values to skip before the first color in the array of colors.
stride Number of colors in the array between rows (must be >= width or public static Bitmap createBitmap (int[] colors, int width, int height, Bitmap.Config config)

Returns a immutable bitmap with the specified width and height, with each pixel value set to the corresponding value in the colors array. Its initial density is as per getDensity() .

Parameters
colors Array of Color used to initialize the pixels. This array must be at least as large as width * height.
width The width of the bitmap
height The height of the bitmap
config The bitmap config to create. If the config does not support per-pixel alpha (e.g. RGB_565), then the alpha bytes in the colors[] will be ignored (assumed to be FF)
Throws
IllegalArgumentException if the width or height are public static Bitmap createScaledBitmap (Bitmap src, int dstWidth, int dstHeight, boolean filter)

Creates a new bitmap, scaled from an existing bitmap, when possible. If the specified width and height are the same as the current width and height of the source bitmap, the source bitmap is returned and no new bitmap is created.

Parameters
src The source bitmap.
dstWidth The new bitmap’s desired width.
dstHeight The new bitmap’s desired height.
filter true if the source should be filtered.
Returns
  • The new scaled bitmap or the source bitmap if no scaling is required.
Throws
IllegalArgumentException if width is public int describeContents ()

No special parcel contents.

Returns
  • a bitmask indicating the set of special object types marshalled by the Parcelable.

public void eraseColor (int c)

Fills the bitmap’s pixels with the specified Color .

Throws

public Bitmap extractAlpha ()

Returns a new bitmap that captures the alpha values of the original. This may be drawn with Canvas.drawBitmap(), where the color(s) will be taken from the paint that is passed to the draw call.

Returns
  • new bitmap containing the alpha channel of the original bitmap.

public Bitmap extractAlpha (Paint paint, int[] offsetXY)

Returns a new bitmap that captures the alpha values of the original. These values may be affected by the optional Paint parameter, which can contain its own alpha, and may also contain a MaskFilter which could change the actual dimensions of the resulting bitmap (e.g. a blur maskfilter might enlarge the resulting bitmap). If offsetXY is not null, it returns the amount to offset the returned bitmap so that it will logically align with the original. For example, if the paint contains a blur of radius 2, then offsetXY[] would contains -2, -2, so that drawing the alpha bitmap offset by (-2, -2) and then drawing the original would result in the blur visually aligning with the original.

The initial density of the returned bitmap is the same as the original’s.

Parameters
paint Optional paint used to modify the alpha values in the resulting bitmap. Pass null for default behavior.
offsetXY Optional array that returns the X (index 0) and Y (index 1) offset needed to position the returned bitmap so that it visually lines up with the original.
Returns
  • new bitmap containing the (optionally modified by paint) alpha channel of the original bitmap. This may be drawn with Canvas.drawBitmap(), where the color(s) will be taken from the paint that is passed to the draw call.

public final int getAllocationByteCount ()

Returns the size of the allocated memory used to store this bitmap’s pixels.

This can be larger than the result of getByteCount() if a bitmap is reused to decode other bitmaps of smaller size, or by manual reconfiguration. See reconfigure(int, int, Config) , setWidth(int) , setHeight(int) , setConfig(Bitmap.Config) , and BitmapFactory.Options.inBitmap . If a bitmap is not modified in this way, this value will be the same as that returned by getByteCount() .

This value will not change over the lifetime of a Bitmap.

See Also

public final int getByteCount ()

Returns the minimum number of bytes that can be used to store this bitmap’s pixels.

As of KITKAT , the result of this method can no longer be used to determine memory usage of a bitmap. See getAllocationByteCount() .

public final Bitmap.Config getConfig ()

If the bitmap’s internal config is in one of the public formats, return that config, otherwise return null.

public int getDensity ()

Returns the density for this bitmap.

The default density is the same density as the current display, unless the current application does not support different screen densities in which case it is DENSITY_DEFAULT . Note that compatibility mode is determined by the application that was initially loaded into a process — applications that share the same process should all have the same compatibility, or ensure they explicitly set the density of their bitmaps appropriately.

Returns
  • A scaling factor of the default density or DENSITY_NONE if the scaling factor is unknown.
See Also

public int getGenerationId ()

Returns the generation ID of this bitmap. The generation ID changes whenever the bitmap is modified. This can be used as an efficient way to check if a bitmap has changed.

Returns
  • The current generation ID for this bitmap.

public final int getHeight ()

Returns the bitmap’s height

public byte[] getNinePatchChunk ()

Returns an optional array of private data, used by the UI system for some bitmaps. Not intended to be called by applications.

public int getPixel (int x, int y)

Returns the Color at the specified location. Throws an exception if x or y are out of bounds (negative or >= to the width or height respectively). The returned color is a non-premultiplied ARGB value.

Parameters
x The x coordinate (0. width-1) of the pixel to return
y The y coordinate (0. height-1) of the pixel to return
Returns
  • The argb Color at the specified coordinate
Throws
IllegalArgumentException if x, y exceed the bitmap’s bounds

public void getPixels (int[] pixels, int offset, int stride, int x, int y, int width, int height)

Returns in pixels[] a copy of the data in the bitmap. Each value is a packed int representing a Color . The stride parameter allows the caller to allow for gaps in the returned pixels array between rows. For normal packed results, just pass width for the stride value. The returned colors are non-premultiplied ARGB values.

Parameters
pixels The array to receive the bitmap’s colors
offset The first index to write into pixels[]
stride The number of entries in pixels[] to skip between rows (must be >= bitmap’s width). Can be negative.
x The x coordinate of the first pixel to read from the bitmap
y The y coordinate of the first pixel to read from the bitmap
width The number of pixels to read from each row
height The number of rows to read
Throws
IllegalArgumentException if x, y, width, height exceed the bounds of the bitmap, or if abs(stride) public final int getRowBytes ()

Return the number of bytes between rows in the bitmap’s pixels. Note that this refers to the pixels as stored natively by the bitmap. If you call getPixels() or setPixels(), then the pixels are uniformly treated as 32bit values, packed according to the Color class.

As of KITKAT , this method should not be used to calculate the memory usage of the bitmap. Instead, see getAllocationByteCount() .

Returns
  • number of bytes between rows of the native bitmap pixels.

public int getScaledHeight (DisplayMetrics metrics)

Convenience for calling getScaledHeight(int) with the target density of the given DisplayMetrics .

public int getScaledHeight (int targetDensity)

Convenience method that returns the height of this bitmap divided by the density scale factor.

Parameters
targetDensity The density of the target canvas of the bitmap.
Returns
  • The scaled height of this bitmap, according to the density scale factor.

public int getScaledHeight (Canvas canvas)

Convenience for calling getScaledHeight(int) with the target density of the given Canvas .

public int getScaledWidth (int targetDensity)

Convenience method that returns the width of this bitmap divided by the density scale factor.

Parameters
targetDensity The density of the target canvas of the bitmap.
Returns
  • The scaled width of this bitmap, according to the density scale factor.

public int getScaledWidth (DisplayMetrics metrics)

Convenience for calling getScaledWidth(int) with the target density of the given DisplayMetrics .

public int getScaledWidth (Canvas canvas)

Convenience for calling getScaledWidth(int) with the target density of the given Canvas .

public final int getWidth ()

Returns the bitmap’s width

public final boolean hasAlpha ()

Returns true if the bitmap’s config supports per-pixel alpha, and if the pixels may contain non-opaque alpha values. For some configs, this is always false (e.g. RGB_565), since they do not support per-pixel alpha. However, for configs that do, the bitmap may be flagged to be known that all of its pixels are opaque. In this case hasAlpha() will also return false. If a config such as ARGB_8888 is not so flagged, it will return true by default.

public final boolean hasMipMap ()

Indicates whether the renderer responsible for drawing this bitmap should attempt to use mipmaps when this bitmap is drawn scaled down. If you know that you are going to draw this bitmap at less than 50% of its original size, you may be able to obtain a higher quality This property is only a suggestion that can be ignored by the renderer. It is not guaranteed to have any effect.

Returns
  • true if the renderer should attempt to use mipmaps, false otherwise
See Also

public final boolean isMutable ()

Returns true if the bitmap is marked as mutable (i.e. can be drawn into)

public final boolean isPremultiplied ()

Indicates whether pixels stored in this bitmaps are stored pre-multiplied. When a pixel is pre-multiplied, the RGB components have been multiplied by the alpha component. For instance, if the original color is a 50% translucent red (128, 255, 0, 0) , the pre-multiplied form is (128, 128, 0, 0) .

This method always returns false if getConfig() is RGB_565 .

The return value is undefined if getConfig() is ALPHA_8 .

This method only returns true if hasAlpha() returns true. A bitmap with no alpha channel can be used both as a pre-multiplied and as a non pre-multiplied bitmap.

Only pre-multiplied bitmaps may be drawn by the view system or Canvas . If a non-pre-multiplied bitmap with an alpha channel is drawn to a Canvas, a RuntimeException will be thrown.

Returns
  • true if the underlying pixels have been pre-multiplied, false otherwise
See Also

public final boolean isRecycled ()

Returns true if this bitmap has been recycled. If so, then it is an error to try to access its pixels, and the bitmap will not draw.

Returns
  • true if the bitmap has been recycled

public void prepareToDraw ()

Rebuilds any caches associated with the bitmap that are used for drawing it. In the case of purgeable bitmaps, this call will attempt to ensure that the pixels have been decoded. If this is called on more than one bitmap in sequence, the priority is given in LRU order (i.e. the last bitmap called will be given highest priority). For bitmaps with no associated caches, this call is effectively a no-op, and therefore is harmless.

public void reconfigure (int width, int height, Bitmap.Config config)

Modifies the bitmap to have a specified width, height, and Bitmap.Config , without affecting the underlying allocation backing the bitmap. Bitmap pixel data is not re-initialized for the new configuration.

This method can be used to avoid allocating a new bitmap, instead reusing an existing bitmap’s allocation for a new configuration of equal or lesser size. If the Bitmap’s allocation isn’t large enough to support the new configuration, an IllegalArgumentException will be thrown and the bitmap will not be modified.

The result of getByteCount() will reflect the new configuration, while getAllocationByteCount() will reflect that of the initial configuration.

Note: This may change this result of hasAlpha(). When converting to 565, the new bitmap will always be considered opaque. When converting from 565, the new bitmap will be considered non-opaque, and will respect the value set by setPremultiplied().

WARNING: This method should NOT be called on a bitmap currently used by the view system. It does not make guarantees about how the underlying pixel buffer is remapped to the new config, just that the allocation is reused. Additionally, the view system does not account for bitmap properties being modifying during use, e.g. while attached to drawables.

See Also

public void recycle ()

Free the native object associated with this bitmap, and clear the reference to the pixel data. This will not free the pixel data synchronously; it simply allows it to be garbage collected if there are no other references. The bitmap is marked as «dead», meaning it will throw an exception if getPixels() or setPixels() is called, and will draw nothing. This operation cannot be reversed, so it should only be called if you are sure there are no further uses for the bitmap. This is an advanced call, and normally need not be called, since the normal GC process will free up this memory when there are no more references to this bitmap.

public boolean sameAs (Bitmap other)

Given another bitmap, return true if it has the same dimensions, config, and pixel data as this bitmap. If any of those differ, return false. If other is null, return false.

public void setConfig (Bitmap.Config config)

Convenience method for calling reconfigure(int, int, Config) with the current height and width.

WARNING: this method should not be used on bitmaps currently used by the view system, see reconfigure(int, int, Config) for more details.

See Also

public void setDensity (int density)

Specifies the density for this bitmap. When the bitmap is drawn to a Canvas that also has a density, it will be scaled appropriately.

Parameters
density The density scaling factor to use with this bitmap or DENSITY_NONE if the density is unknown.
See Also

public void setHasAlpha (boolean hasAlpha)

Tell the bitmap if all of the pixels are known to be opaque (false) or if some of the pixels may contain non-opaque alpha values (true). Note, for some configs (e.g. RGB_565) this call is ignored, since it does not support per-pixel alpha values. This is meant as a drawing hint, as in some cases a bitmap that is known to be opaque can take a faster drawing case than one that may have non-opaque per-pixel alpha values.

public final void setHasMipMap (boolean hasMipMap)

Set a hint for the renderer responsible for drawing this bitmap indicating that it should attempt to use mipmaps when this bitmap is drawn scaled down. If you know that you are going to draw this bitmap at less than 50% of its original size, you may be able to obtain a higher quality by turning this property on. Note that if the renderer respects this hint it might have to allocate extra memory to hold the mipmap levels for this bitmap. This property is only a suggestion that can be ignored by the renderer. It is not guaranteed to have any effect.

Источник

Читайте также:  Createprocess error 2 не удается найти указанный файл android studio
Оцените статью