ОбезьянаИзображение
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Класс обезьяньего бегуна для хранения изображения устройства или экрана эмулятора. Изображение копируется из буфера экрана во время создания скриншота. Методы этого объекта позволяют конвертировать изображение в различные форматы хранения, записывать изображение в файл, копировать части изображения и сравнивать этот объект с другими объектами MonkeyImage
.
Вам не нужно создавать новые экземпляры MonkeyImage
. Вместо этого используйте MonkeyDevice.takeSnapshot()
чтобы создать новый экземпляр из снимка экрана. Например, используйте:
newimage = MonkeyDevice.takeSnapshot()
Краткое содержание
Методы |
---|
нить | ConvertToBytes ( строковый формат) Преобразует текущее изображение в определенный формат и возвращает его в виде строки , к которой затем можно получить доступ как к итерации двоичных байтов. |
кортеж | getRawPixel ( целое число x, целое число y) Возвращает один пиксель в местоположении изображения (x,y) как кортеж целых чисел в форме (a,r,g,b). |
целое число | getRawPixelInt ( целое число x, целое число y) Возвращает один пиксель в местоположении изображения (x,y) в виде 32-битного целого числа . |
MonkeyImage | getSubImage ( кортеж прямоугольник) Создает новый объект MonkeyImage из прямоугольного выделения текущего изображения. |
логическое значение | SameAs ( MonkeyImage другое, процент с плавающей запятой ) Сравнивает этот объект MonkeyImage с другим и возвращает результат сравнения. Аргумент percent указывает разницу в процентах, при которой два изображения могут быть «равными». |
пустота | writeToFile (путь к строке , формат строки ) Записывает текущее изображение в файл, указанный в параметре filename , в формате, указанном в format . |
Публичные методы
Преобразует текущее изображение в определенный формат и возвращает его в виде строки , к которой затем можно получить доступ как к итерации двоичных байтов.
Аргументы
формат | Желаемый формат вывода. Поддерживаются все распространенные форматы растрового вывода. Значение по умолчанию — «png» (переносимая сетевая графика). |
---|
кортеж getRawPixel ( целое число x, целое число y)
Возвращает один пиксель в местоположении изображения (x,y) как кортеж целых чисел в форме (a,r,g,b).
Аргументы
х | Горизонтальное положение пикселя, начиная с 0, слева от экрана в той ориентации, которую он имел при создании снимка экрана. |
---|
й | Вертикальное положение пикселя, начиная с 0 в верхней части экрана, в той ориентации, которую он имел при создании снимка экрана. |
---|
Возврат
- Кортеж целых чисел, представляющих пиксель, в форме (a,r,g,b), где a — значение альфа-канала, а r, g и b — значения красного, зеленого и синего соответственно.
кортеж getRawPixelInt ( целое число x, целое число y)
Возвращает один пиксель в местоположении изображения (x,y) в виде целого числа . Используйте этот метод, чтобы сэкономить память.
Аргументы
х | Горизонтальное положение пикселя, начиная с 0, слева от экрана в той ориентации, которую он имел при создании снимка экрана. |
---|
й | Вертикальное положение пикселя, начиная с 0 в верхней части экрана, в той ориентации, которую он имел при создании снимка экрана. |
---|
Возврат
- Значения a,r,g и b пикселя представляют собой 8-битные значения, объединенные в 32-битное целое число, где a — самые левые 8 бит, r — следующие самые правые и т. д.
MonkeyImage
getSubImage ( кортеж прямоугольник)
Создает новый объект MonkeyImage
из прямоугольного выделения текущего изображения.
Аргументы
прямой | Кортеж (x, y, w, h), определяющий выбор. x и y определяют положение пикселя верхнего левого угла выделения, отсчитываемое от 0. w определяет ширину области, а h определяет ее высоту, как в пикселях. Ориентация изображения такая же, как ориентация экрана на момент создания снимка экрана. |
---|
Возврат
- Новый объект
MonkeyImage
, содержащий выделение.
логическое значение SameAs ( MonkeyImage
, процент с плавающей запятой )
Сравнивает этот объект MonkeyImage
с другим и возвращает результат сравнения. Аргумент percent
указывает разницу в процентах, при которой два изображения могут быть «равными».
Аргументы
другой | Еще один объект MonkeyImage для сравнения с этим. |
---|
процент | Число с плавающей запятой в диапазоне от 0,0 до 1,0 включительно, указывающее процент пикселей, которые должны быть одинаковыми, чтобы метод возвращал true . Значение по умолчанию — 1,0, что означает, что все пиксели должны совпадать. |
---|
Возврат
- Логическое значение
true
, если изображения совпадают, или логическое значение false
в противном случае.
Записывает текущее изображение в файл, указанный в параметре filename
, в формате, указанном в format
.
Аргументы
путь | Полное имя файла и расширение выходного файла. |
---|
формат | Выходной формат, используемый для файла. Если формат не указан, метод пытается угадать формат по расширению имени файла. Если расширение не указано и формат не указан, то используется формат по умолчанию «png» (переносимая сетевая графика). |
---|
Контент и образцы кода на этой странице предоставлены по лицензиям. Java и OpenJDK – это зарегистрированные товарные знаки корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-07-29 UTC.
[[["Прост для понимания","easyToUnderstand","thumb-up"],["Помог мне решить мою проблему","solvedMyProblem","thumb-up"],["Другое","otherUp","thumb-up"]],[["Отсутствует нужная мне информация","missingTheInformationINeed","thumb-down"],["Слишком сложен/слишком много шагов","tooComplicatedTooManySteps","thumb-down"],["Устарел","outOfDate","thumb-down"],["Проблема с переводом текста","translationIssue","thumb-down"],["Проблемы образцов/кода","samplesCodeIssue","thumb-down"],["Другое","otherDown","thumb-down"]],["Последнее обновление: 2025-07-29 UTC."],[],[],null,["# MonkeyImage\n\nA monkeyrunner class to hold an image of the device or emulator's screen. The image is\ncopied from the screen buffer during a screenshot. This object's methods allow you to\nconvert the image into various storage formats, write the image to a file, copy parts of\nthe image, and compare this object to other `MonkeyImage` objects.\n\n\nYou do not need to create new instances of `MonkeyImage`. Instead, use\n[MonkeyDevice.takeSnapshot()](/tools/help/MonkeyDevice#takeSnapshot) to create a new instance from a screenshot. For example, use: \n\n```\nnewimage = MonkeyDevice.takeSnapshot()\n```\n\nSummary\n-------\n\n| Methods ||||||||||||\n|----------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---|---|---|---|---|---|---|---|---|---|\n| *string* | [convertToBytes](#convertToBytes) (*string* format) Converts the current image to a particular format and returns it as a *string* that you can then access as an *iterable* of binary bytes. |\n| *tuple* | [getRawPixel](#getRawPixel) (*integer* x, *integer* y) Returns the single pixel at the image location (x,y), as an a *tuple* of *integer*, in the form (a,r,g,b). |\n| *integer* | [getRawPixelInt](#getRawPixelInt) (*integer* x, *integer* y) Returns the single pixel at the image location (x,y), as a 32-bit *integer*. |\n| ` `[MonkeyImage](/tools/help/MonkeyImage)` ` | [getSubImage](#getSubImage) (*tuple* rect) Creates a new `MonkeyImage` object from a rectangular selection of the current image. |\n| *boolean* | [sameAs](#sameAs) ([MonkeyImage](/tools/help/MonkeyImage) other, *float* percent) Compares this `MonkeyImage` object to another and returns the result of the comparison. The `percent` argument specifies the percentage difference that is allowed for the two images to be \"equal\". |\n| *void* | [writeToFile](#writeToFile) (*string* path, *string* format) Writes the current image to the file specified by `filename`, in the format specified by `format`. |\n\nPublic methods\n--------------\n\n#### *string*\nconvertToBytes\n( *string* format)\n\n\nConverts the current image to a particular format and returns it as a *string*\nthat you can then access as an *iterable* of binary bytes. \n\n##### Arguments\n\n| format | The desired output format. All of the common raster output formats are supported. The default value is \"png\" (Portable Network Graphics). |\n|--------|-------------------------------------------------------------------------------------------------------------------------------------------|\n\n#### *tuple*\ngetRawPixel\n(*integer* x, *integer* y)\n\n\nReturns the single pixel at the image location (x,y), as an\na *tuple* of *integer*, in the form (a,r,g,b). \n\n##### Arguments\n\n| x | The horizontal position of the pixel, starting with 0 at the left of the screen in the orientation it had when the screenshot was taken. |\n| y | The vertical position of the pixel, starting with 0 at the top of the screen in the orientation it had when the screenshot was taken. |\n|---|------------------------------------------------------------------------------------------------------------------------------------------|\n\n##### Returns\n\n- A tuple of integers representing the pixel, in the form (a,r,g,b) where a is the alpha channel value, and r, g, and b are the red, green, and blue values, respectively. \n\n#### *tuple*\ngetRawPixelInt\n(*integer* x, *integer* y)\n\n\nReturns the single pixel at the image location (x,y), as an\nan *integer*. Use this method to economize on memory. \n\n##### Arguments\n\n| x | The horizontal position of the pixel, starting with 0 at the left of the screen in the orientation it had when the screenshot was taken. |\n| y | The vertical position of the pixel, starting with 0 at the top of the screen in the orientation it had when the screenshot was taken. |\n|---|------------------------------------------------------------------------------------------------------------------------------------------|\n\n##### Returns\n\n- The a,r,g, and b values of the pixel as 8-bit values combined into a 32-bit integer, with a as the leftmost 8 bits, r the next rightmost, and so forth. \n\n#### `\n`[MonkeyImage](/tools/help/MonkeyImage)`\n`\ngetSubImage\n(*tuple* rect)\n\n\nCreates a new `MonkeyImage` object from a rectangular selection of the\ncurrent image. \n\n##### Arguments\n\n| rect | A tuple (x, y, w, h) specifying the selection. x and y specify the 0-based pixel position of the upper left-hand corner of the selection. w specifies the width of the region, and h specifies its height, both in units of pixels. The image's orientation is the same as the screen orientation at the time the screenshot was made. |\n|------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n\n##### Returns\n\n- A new `MonkeyImage` object containing the selection. \n\n#### *boolean*\nsameAs\n( `\n`[MonkeyImage](/tools/help/MonkeyImage)`\n` otherImage, *float* percent )\n\n\nCompares this `MonkeyImage` object to another and returns the result of\nthe comparison. The `percent` argument specifies the percentage\ndifference that is allowed for the two images to be \"equal\". \n\n##### Arguments\n\n| other | Another `MonkeyImage` object to compare to this one. |\n| percent | A float in the range 0.0 to 1.0, inclusive, indicating the percentage of pixels that need to be the same for the method to return `true`. The default is 1.0, indicating that all the pixels must match. |\n|---------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n\n##### Returns\n\n- Boolean `true` if the images match, or boolean `false` otherwise. \n\n#### void\nwriteToFile\n(*string* filename, *string* format)\n\n\nWrites the current image to the file specified by `filename`, in the\nformat specified by `format`. \n\n##### Arguments\n\n| path | The fully-qualified filename and extension of the output file. |\n| format | The output format to use for the file. If no format is provided, then the method tries to guess the format from the filename's extension. If no extension is provided and no format is specified, then the default format of \"png\" (Portable Network Graphics) is used. |\n|--------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|"]]