• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2012 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #ifndef SkImage_DEFINED
9 #define SkImage_DEFINED
10 
11 #include "include/core/SkAlphaType.h"
12 #include "include/core/SkImageInfo.h"
13 #include "include/core/SkRect.h"
14 #include "include/core/SkRefCnt.h"
15 #include "include/core/SkSize.h"
16 #include "include/core/SkTypes.h"
17 
18 #if defined(SK_GANESH)
19 #include "include/gpu/GpuTypes.h"
20 #include "include/gpu/GrTypes.h"
21 #endif
22 #if defined(SK_GRAPHITE)
23 #include "include/gpu/graphite/GraphiteTypes.h"
24 #endif
25 
26 #include <cstddef>
27 #include <cstdint>
28 #include <functional>
29 #include <memory>
30 #include <optional>
31 
32 #if defined(SK_BUILD_FOR_ANDROID) && __ANDROID_API__ >= 26
33 #include "include/gpu/GrTypes.h"
34 #include <android/hardware_buffer.h>
35 #endif
36 
37 class GrBackendFormat;
38 class GrBackendTexture;
39 class GrContextThreadSafeProxy;
40 class GrDirectContext;
41 class GrRecordingContext;
42 class GrYUVABackendTextureInfo;
43 class GrYUVABackendTextures;
44 class SkBitmap;
45 class SkColorSpace;
46 class SkData;
47 class SkImageFilter;
48 class SkImageGenerator;
49 class SkMatrix;
50 class SkMipmap;
51 class SkPaint;
52 class SkPicture;
53 class SkPixmap;
54 class SkPromiseImageTexture;
55 class SkShader;
56 class SkSurfaceProps;
57 class SkYUVAPixmaps;
58 enum SkColorType : int;
59 enum class SkEncodedImageFormat;
60 enum class SkTileMode;
61 struct SkIPoint;
62 struct SkSamplingOptions;
63 
64 #if defined(SK_GRAPHITE)
65 namespace skgpu::graphite {
66 class BackendTexture;
67 class Recorder;
68 class TextureInfo;
69 enum class Volatile : bool;
70 }
71 #endif
72 
73 /** \class SkImage
74     SkImage describes a two dimensional array of pixels to draw. The pixels may be
75     decoded in a raster bitmap, encoded in a SkPicture or compressed data stream,
76     or located in GPU memory as a GPU texture.
77 
78     SkImage cannot be modified after it is created. SkImage may allocate additional
79     storage as needed; for instance, an encoded SkImage may decode when drawn.
80 
81     SkImage width and height are greater than zero. Creating an SkImage with zero width
82     or height returns SkImage equal to nullptr.
83 
84     SkImage may be created from SkBitmap, SkPixmap, SkSurface, SkPicture, encoded streams,
85     GPU texture, YUV_ColorSpace data, or hardware buffer. Encoded streams supported
86     include BMP, GIF, HEIF, ICO, JPEG, PNG, WBMP, WebP. Supported encoding details
87     vary with platform.
88 */
89 class SK_API SkImage : public SkRefCnt {
90 public:
91 
92     /** Caller data passed to RasterReleaseProc; may be nullptr.
93     */
94     typedef void* ReleaseContext;
95 
96     /** Creates SkImage from SkPixmap and copy of pixels. Since pixels are copied, SkPixmap
97         pixels may be modified or deleted without affecting SkImage.
98 
99         SkImage is returned if SkPixmap is valid. Valid SkPixmap parameters include:
100         dimensions are greater than zero;
101         each dimension fits in 29 bits;
102         SkColorType and SkAlphaType are valid, and SkColorType is not kUnknown_SkColorType;
103         row bytes are large enough to hold one row of pixels;
104         pixel address is not nullptr.
105 
106         @param pixmap  SkImageInfo, pixel address, and row bytes
107         @return        copy of SkPixmap pixels, or nullptr
108 
109         example: https://fiddle.skia.org/c/@Image_MakeRasterCopy
110     */
111     static sk_sp<SkImage> MakeRasterCopy(const SkPixmap& pixmap);
112 
113     /** Creates SkImage from SkImageInfo, sharing pixels.
114 
115         SkImage is returned if SkImageInfo is valid. Valid SkImageInfo parameters include:
116         dimensions are greater than zero;
117         each dimension fits in 29 bits;
118         SkColorType and SkAlphaType are valid, and SkColorType is not kUnknown_SkColorType;
119         rowBytes are large enough to hold one row of pixels;
120         pixels is not nullptr, and contains enough data for SkImage.
121 
122         @param info      contains width, height, SkAlphaType, SkColorType, SkColorSpace
123         @param pixels    address or pixel storage
124         @param rowBytes  size of pixel row or larger
125         @return          SkImage sharing pixels, or nullptr
126     */
127     static sk_sp<SkImage> MakeRasterData(const SkImageInfo& info, sk_sp<SkData> pixels,
128                                          size_t rowBytes);
129 
130     /** Function called when SkImage no longer shares pixels. ReleaseContext is
131         provided by caller when SkImage is created, and may be nullptr.
132     */
133     typedef void (*RasterReleaseProc)(const void* pixels, ReleaseContext);
134 
135     /** Creates SkImage from pixmap, sharing SkPixmap pixels. Pixels must remain valid and
136         unchanged until rasterReleaseProc is called. rasterReleaseProc is passed
137         releaseContext when SkImage is deleted or no longer refers to pixmap pixels.
138 
139         Pass nullptr for rasterReleaseProc to share SkPixmap without requiring a callback
140         when SkImage is released. Pass nullptr for releaseContext if rasterReleaseProc
141         does not require state.
142 
143         SkImage is returned if pixmap is valid. Valid SkPixmap parameters include:
144         dimensions are greater than zero;
145         each dimension fits in 29 bits;
146         SkColorType and SkAlphaType are valid, and SkColorType is not kUnknown_SkColorType;
147         row bytes are large enough to hold one row of pixels;
148         pixel address is not nullptr.
149 
150         @param pixmap             SkImageInfo, pixel address, and row bytes
151         @param rasterReleaseProc  function called when pixels can be released; or nullptr
152         @param releaseContext     state passed to rasterReleaseProc; or nullptr
153         @return                   SkImage sharing pixmap
154     */
155     static sk_sp<SkImage> MakeFromRaster(const SkPixmap& pixmap,
156                                          RasterReleaseProc rasterReleaseProc,
157                                          ReleaseContext releaseContext);
158 
159     /** Creates SkImage from bitmap, sharing or copying bitmap pixels. If the bitmap
160         is marked immutable, and its pixel memory is shareable, it may be shared
161         instead of copied.
162 
163         SkImage is returned if bitmap is valid. Valid SkBitmap parameters include:
164         dimensions are greater than zero;
165         each dimension fits in 29 bits;
166         SkColorType and SkAlphaType are valid, and SkColorType is not kUnknown_SkColorType;
167         row bytes are large enough to hold one row of pixels;
168         pixel address is not nullptr.
169 
170         @param bitmap  SkImageInfo, row bytes, and pixels
171         @return        created SkImage, or nullptr
172 
173         example: https://fiddle.skia.org/c/@Image_MakeFromBitmap
174     */
175     static sk_sp<SkImage> MakeFromBitmap(const SkBitmap& bitmap);
176 
177     /** Creates SkImage from data returned by imageGenerator. Generated data is owned by SkImage and
178         may not be shared or accessed.
179 
180         SkImage is returned if generator data is valid. Valid data parameters vary by type of data
181         and platform.
182 
183         imageGenerator may wrap SkPicture data, codec data, or custom data.
184 
185         @param imageGenerator  stock or custom routines to retrieve SkImage
186         @return                created SkImage, or nullptr
187     */
188     static sk_sp<SkImage> MakeFromGenerator(std::unique_ptr<SkImageGenerator> imageGenerator);
189 
190     /**
191      *  Return an image backed by the encoded data, but attempt to defer decoding until the image
192      *  is actually used/drawn. This deferral allows the system to cache the result, either on the
193      *  CPU or on the GPU, depending on where the image is drawn. If memory is low, the cache may
194      *  be purged, causing the next draw of the image to have to re-decode.
195      *
196      *  If alphaType is nullopt, the image's alpha type will be chosen automatically based on the
197      *  image format. Transparent images will default to kPremul_SkAlphaType. If alphaType contains
198      *  kPremul_SkAlphaType or kUnpremul_SkAlphaType, that alpha type will be used. Forcing opaque
199      *  (passing kOpaque_SkAlphaType) is not allowed, and will return nullptr.
200      *
201      *  This is similar to DecodeTo[Raster,Texture], but this method will attempt to defer the
202      *  actual decode, while the DecodeTo... method explicitly decode and allocate the backend
203      *  when the call is made.
204      *
205      *  If the encoded format is not supported, nullptr is returned.
206      *
207      *  @param encoded  the encoded data
208      *  @return         created SkImage, or nullptr
209 
210         example: https://fiddle.skia.org/c/@Image_MakeFromEncoded
211     */
212     static sk_sp<SkImage> MakeFromEncoded(sk_sp<SkData> encoded,
213                                           std::optional<SkAlphaType> alphaType = std::nullopt);
214 
215     /*
216      * Experimental:
217      *   Skia                | GL_COMPRESSED_*     | MTLPixelFormat*      | VK_FORMAT_*_BLOCK
218      *  --------------------------------------------------------------------------------------
219      *   kETC2_RGB8_UNORM    | ETC1_RGB8           | ETC2_RGB8 (iOS-only) | ETC2_R8G8B8_UNORM
220      *                       | RGB8_ETC2           |                      |
221      *  --------------------------------------------------------------------------------------
222      *   kBC1_RGB8_UNORM     | RGB_S3TC_DXT1_EXT   | N/A                  | BC1_RGB_UNORM
223      *  --------------------------------------------------------------------------------------
224      *   kBC1_RGBA8_UNORM    | RGBA_S3TC_DXT1_EXT  | BC1_RGBA (macOS-only)| BC1_RGBA_UNORM
225      */
226     enum class CompressionType {
227         kNone,
228         kETC2_RGB8_UNORM, // the same as ETC1
229 
230         kBC1_RGB8_UNORM,
231         kBC1_RGBA8_UNORM,
232         kLast = kBC1_RGBA8_UNORM,
233     };
234 
235     static constexpr int kCompressionTypeCount = static_cast<int>(CompressionType::kLast) + 1;
236 
237     static const CompressionType kETC1_CompressionType = CompressionType::kETC2_RGB8_UNORM;
238 
239     /** Creates a CPU-backed SkImage from compressed data.
240 
241         This method will decompress the compressed data and create an image wrapping
242         it. Any mipmap levels present in the compressed data are discarded.
243 
244         @param data     compressed data to store in SkImage
245         @param width    width of full SkImage
246         @param height   height of full SkImage
247         @param type     type of compression used
248         @return         created SkImage, or nullptr
249     */
250     static sk_sp<SkImage> MakeRasterFromCompressed(sk_sp<SkData> data,
251                                                    int width, int height,
252                                                    CompressionType type);
253 
254     enum class BitDepth {
255         kU8,  //!< uses 8-bit unsigned int per color component
256         kF16, //!< uses 16-bit float per color component
257     };
258 
259     /** Creates SkImage from picture. Returned SkImage width and height are set by dimensions.
260         SkImage draws picture with matrix and paint, set to bitDepth and colorSpace.
261 
262         If matrix is nullptr, draws with identity SkMatrix. If paint is nullptr, draws
263         with default SkPaint. colorSpace may be nullptr.
264 
265         @param picture     stream of drawing commands
266         @param dimensions  width and height
267         @param matrix      SkMatrix to rotate, scale, translate, and so on; may be nullptr
268         @param paint       SkPaint to apply transparency, filtering, and so on; may be nullptr
269         @param bitDepth    8-bit integer or 16-bit float: per component
270         @param colorSpace  range of colors; may be nullptr
271         @param props       props to use when rasterizing the picture
272         @return            created SkImage, or nullptr
273     */
274     static sk_sp<SkImage> MakeFromPicture(sk_sp<SkPicture> picture, const SkISize& dimensions,
275                                           const SkMatrix* matrix, const SkPaint* paint,
276                                           BitDepth bitDepth, sk_sp<SkColorSpace> colorSpace,
277                                           SkSurfaceProps props);
278     static sk_sp<SkImage> MakeFromPicture(sk_sp<SkPicture> picture, const SkISize& dimensions,
279                                           const SkMatrix* matrix, const SkPaint* paint,
280                                           BitDepth bitDepth, sk_sp<SkColorSpace> colorSpace);
281 
282 #if defined(SK_GANESH)
283         /** Creates a GPU-backed SkImage from compressed data.
284 
285         This method will return an SkImage representing the compressed data.
286         If the GPU doesn't support the specified compression method, the data
287         will be decompressed and then wrapped in a GPU-backed image.
288 
289         Note: one can query the supported compression formats via
290         GrRecordingContext::compressedBackendFormat.
291 
292         @param context     GPU context
293         @param data        compressed data to store in SkImage
294         @param width       width of full SkImage
295         @param height      height of full SkImage
296         @param type        type of compression used
297         @param mipmapped   does 'data' contain data for all the mipmap levels?
298         @param isProtected do the contents of 'data' require DRM protection (on Vulkan)?
299         @return            created SkImage, or nullptr
300     */
301     static sk_sp<SkImage> MakeTextureFromCompressed(GrDirectContext* direct,
302                                                     sk_sp<SkData> data,
303                                                     int width, int height,
304                                                     CompressionType type,
305                                                     GrMipmapped mipmapped = GrMipmapped::kNo,
306                                                     GrProtected isProtected = GrProtected::kNo);
307 
308     /** User function called when supplied texture may be deleted.
309     */
310     typedef void (*TextureReleaseProc)(ReleaseContext releaseContext);
311 
312     /** Creates SkImage from GPU texture associated with context. GPU texture must stay
313         valid and unchanged until textureReleaseProc is called. textureReleaseProc is
314         passed releaseContext when SkImage is deleted or no longer refers to texture.
315 
316         SkImage is returned if format of backendTexture is recognized and supported.
317         Recognized formats vary by GPU back-end.
318 
319         @note When using a DDL recording context, textureReleaseProc will be called on the
320         GPU thread after the DDL is played back on the direct context.
321 
322         @param context             GPU context
323         @param backendTexture      texture residing on GPU
324         @param colorSpace          This describes the color space of this image's contents, as
325                                    seen after sampling. In general, if the format of the backend
326                                    texture is SRGB, some linear colorSpace should be supplied
327                                    (e.g., SkColorSpace::MakeSRGBLinear()). If the format of the
328                                    backend texture is linear, then the colorSpace should include
329                                    a description of the transfer function as
330                                    well (e.g., SkColorSpace::MakeSRGB()).
331         @param textureReleaseProc  function called when texture can be released
332         @param releaseContext      state passed to textureReleaseProc
333         @return                    created SkImage, or nullptr
334     */
335     static sk_sp<SkImage> MakeFromTexture(GrRecordingContext* context,
336                                           const GrBackendTexture& backendTexture,
337                                           GrSurfaceOrigin origin,
338                                           SkColorType colorType,
339                                           SkAlphaType alphaType,
340                                           sk_sp<SkColorSpace> colorSpace,
341                                           TextureReleaseProc textureReleaseProc = nullptr,
342                                           ReleaseContext releaseContext = nullptr);
343 
344     /** Creates an SkImage from a GPU backend texture. The backend texture must stay
345         valid and unchanged until textureReleaseProc is called. The textureReleaseProc is
346         called when the SkImage is deleted or no longer refers to the texture and will be
347         passed the releaseContext.
348 
349         An SkImage is returned if the format of backendTexture is recognized and supported.
350         Recognized formats vary by GPU back-end.
351 
352         @note When using a DDL recording context, textureReleaseProc will be called on the
353         GPU thread after the DDL is played back on the direct context.
354 
355         @param context             the GPU context
356         @param backendTexture      a texture already allocated by the GPU
357         @param alphaType           This characterizes the nature of the alpha values in the
358                                    backend texture. For opaque compressed formats (e.g., ETC1)
359                                    this should usually be set to kOpaque_SkAlphaType.
360         @param colorSpace          This describes the color space of this image's contents, as
361                                    seen after sampling. In general, if the format of the backend
362                                    texture is SRGB, some linear colorSpace should be supplied
363                                    (e.g., SkColorSpace::MakeSRGBLinear()). If the format of the
364                                    backend texture is linear, then the colorSpace should include
365                                    a description of the transfer function as
366                                    well (e.g., SkColorSpace::MakeSRGB()).
367         @param textureReleaseProc  function called when the backend texture can be released
368         @param releaseContext      state passed to textureReleaseProc
369         @return                    created SkImage, or nullptr
370     */
371     static sk_sp<SkImage> MakeFromCompressedTexture(GrRecordingContext* context,
372                                                     const GrBackendTexture& backendTexture,
373                                                     GrSurfaceOrigin origin,
374                                                     SkAlphaType alphaType,
375                                                     sk_sp<SkColorSpace> colorSpace,
376                                                     TextureReleaseProc textureReleaseProc = nullptr,
377                                                     ReleaseContext releaseContext = nullptr);
378 
379     /** Creates SkImage from pixmap. SkImage is uploaded to GPU back-end using context.
380 
381         Created SkImage is available to other GPU contexts, and is available across thread
382         boundaries. All contexts must be in the same GPU share group, or otherwise
383         share resources.
384 
385         When SkImage is no longer referenced, context releases texture memory
386         asynchronously.
387 
388         SkColorSpace of SkImage is determined by pixmap.colorSpace().
389 
390         SkImage is returned referring to GPU back-end if context is not nullptr,
391         format of data is recognized and supported, and if context supports moving
392         resources between contexts. Otherwise, pixmap pixel data is copied and SkImage
393         as returned in raster format if possible; nullptr may be returned.
394         Recognized GPU formats vary by platform and GPU back-end.
395 
396         @param context                GPU context
397         @param pixmap                 SkImageInfo, pixel address, and row bytes
398         @param buildMips              create SkImage as mip map if true
399         @param limitToMaxTextureSize  downscale image to GPU maximum texture size, if necessary
400         @return                       created SkImage, or nullptr
401     */
402     static sk_sp<SkImage> MakeCrossContextFromPixmap(GrDirectContext* context,
403                                                      const SkPixmap& pixmap,
404                                                      bool buildMips,
405                                                      bool limitToMaxTextureSize = false);
406 
407     /** Creates SkImage from backendTexture associated with context. backendTexture and
408         returned SkImage are managed internally, and are released when no longer needed.
409 
410         SkImage is returned if format of backendTexture is recognized and supported.
411         Recognized formats vary by GPU back-end.
412 
413         @param context         GPU context
414         @param backendTexture  texture residing on GPU
415         @param textureOrigin   origin of backendTexture
416         @param colorType       color type of the resulting image
417         @param alphaType       alpha type of the resulting image
418         @param colorSpace      range of colors; may be nullptr
419         @return                created SkImage, or nullptr
420     */
421     static sk_sp<SkImage> MakeFromAdoptedTexture(GrRecordingContext* context,
422                                                  const GrBackendTexture& backendTexture,
423                                                  GrSurfaceOrigin textureOrigin,
424                                                  SkColorType colorType);
425     static sk_sp<SkImage> MakeFromAdoptedTexture(GrRecordingContext* context,
426                                                  const GrBackendTexture& backendTexture,
427                                                  GrSurfaceOrigin textureOrigin,
428                                                  SkColorType colorType,
429                                                  SkAlphaType alphaType);
430     static sk_sp<SkImage> MakeFromAdoptedTexture(GrRecordingContext* context,
431                                                  const GrBackendTexture& backendTexture,
432                                                  GrSurfaceOrigin textureOrigin,
433                                                  SkColorType colorType,
434                                                  SkAlphaType alphaType,
435                                                  sk_sp<SkColorSpace> colorSpace);
436 
437     /** Creates an SkImage from YUV[A] planar textures. This requires that the textures stay valid
438         for the lifetime of the image. The ReleaseContext can be used to know when it is safe to
439         either delete or overwrite the textures. If ReleaseProc is provided it is also called before
440         return on failure.
441 
442         @param context            GPU context
443         @param yuvaTextures       A set of textures containing YUVA data and a description of the
444                                   data and transformation to RGBA.
445         @param imageColorSpace    range of colors of the resulting image after conversion to RGB;
446                                   may be nullptr
447         @param textureReleaseProc called when the backend textures can be released
448         @param releaseContext     state passed to textureReleaseProc
449         @return                   created SkImage, or nullptr
450     */
451     static sk_sp<SkImage> MakeFromYUVATextures(GrRecordingContext* context,
452                                                const GrYUVABackendTextures& yuvaTextures,
453                                                sk_sp<SkColorSpace> imageColorSpace,
454                                                TextureReleaseProc textureReleaseProc = nullptr,
455                                                ReleaseContext releaseContext = nullptr);
456     static sk_sp<SkImage> MakeFromYUVATextures(GrRecordingContext* context,
457                                                const GrYUVABackendTextures& yuvaTextures);
458 
459     /** Creates SkImage from SkYUVAPixmaps.
460 
461         The image will remain planar with each plane converted to a texture using the passed
462         GrRecordingContext.
463 
464         SkYUVAPixmaps has a SkYUVAInfo which specifies the transformation from YUV to RGB.
465         The SkColorSpace of the resulting RGB values is specified by imageColorSpace. This will
466         be the SkColorSpace reported by the image and when drawn the RGB values will be converted
467         from this space into the destination space (if the destination is tagged).
468 
469         Currently, this is only supported using the GPU backend and will fail if context is nullptr.
470 
471         SkYUVAPixmaps does not need to remain valid after this returns.
472 
473         @param context                GPU context
474         @param pixmaps                The planes as pixmaps with supported SkYUVAInfo that
475                                       specifies conversion to RGB.
476         @param buildMips              create internal YUVA textures as mip map if kYes. This is
477                                       silently ignored if the context does not support mip maps.
478         @param limitToMaxTextureSize  downscale image to GPU maximum texture size, if necessary
479         @param imageColorSpace        range of colors of the resulting image; may be nullptr
480         @return                       created SkImage, or nullptr
481     */
482     static sk_sp<SkImage> MakeFromYUVAPixmaps(GrRecordingContext* context,
483                                               const SkYUVAPixmaps& pixmaps,
484                                               GrMipmapped buildMips,
485                                               bool limitToMaxTextureSize,
486                                               sk_sp<SkColorSpace> imageColorSpace);
487     static sk_sp<SkImage> MakeFromYUVAPixmaps(GrRecordingContext* context,
488                                               const SkYUVAPixmaps& pixmaps,
489                                               GrMipmapped buildMips = GrMipmapped::kNo,
490                                               bool limitToMaxTextureSize = false);
491 
492     using PromiseImageTextureContext = void*;
493     using PromiseImageTextureFulfillProc =
494             sk_sp<SkPromiseImageTexture> (*)(PromiseImageTextureContext);
495     using PromiseImageTextureReleaseProc = void (*)(PromiseImageTextureContext);
496 
497     /** Create a new SkImage that is very similar to an SkImage created by MakeFromTexture. The
498         difference is that the caller need not have created the texture nor populated it with the
499         image pixel data. Moreover, the SkImage may be created on a thread as the creation of the
500         image does not require access to the backend API or GrDirectContext. Instead of passing a
501         GrBackendTexture the client supplies a description of the texture consisting of
502         GrBackendFormat, width, height, and GrMipmapped state. The resulting SkImage can be drawn
503         to a SkDeferredDisplayListRecorder or directly to a GPU-backed SkSurface.
504 
505         When the actual texture is required to perform a backend API draw, textureFulfillProc will
506         be called to receive a GrBackendTexture. The properties of the GrBackendTexture must match
507         those set during the SkImage creation, and it must refer to a valid existing texture in the
508         backend API context/device, and be populated with the image pixel data. The texture cannot
509         be deleted until textureReleaseProc is called.
510 
511         There is at most one call to each of textureFulfillProc and textureReleaseProc.
512         textureReleaseProc is always called even if image creation fails or if the
513         image is never fulfilled (e.g. it is never drawn or all draws are clipped out)
514 
515         @param gpuContextProxy     the thread-safe proxy of the gpu context. required.
516         @param backendFormat       format of promised gpu texture
517         @param dimensions          width & height of promised gpu texture
518         @param mipmapped           mip mapped state of promised gpu texture
519         @param origin              surface origin of promised gpu texture
520         @param colorType           color type of promised gpu texture
521         @param alphaType           alpha type of promised gpu texture
522         @param colorSpace          range of colors; may be nullptr
523         @param textureFulfillProc  function called to get actual gpu texture
524         @param textureReleaseProc  function called when texture can be deleted
525         @param textureContext      state passed to textureFulfillProc and textureReleaseProc
526         @return                    created SkImage, or nullptr
527     */
528     static sk_sp<SkImage> MakePromiseTexture(sk_sp<GrContextThreadSafeProxy> gpuContextProxy,
529                                              const GrBackendFormat& backendFormat,
530                                              SkISize dimensions,
531                                              GrMipmapped mipmapped,
532                                              GrSurfaceOrigin origin,
533                                              SkColorType colorType,
534                                              SkAlphaType alphaType,
535                                              sk_sp<SkColorSpace> colorSpace,
536                                              PromiseImageTextureFulfillProc textureFulfillProc,
537                                              PromiseImageTextureReleaseProc textureReleaseProc,
538                                              PromiseImageTextureContext textureContext);
539 
540     /** This entry point operates like 'MakePromiseTexture' but it is used to construct a SkImage
541         from YUV[A] data. The source data may be planar (i.e. spread across multiple textures). In
542         the extreme Y, U, V, and A are all in different planes and thus the image is specified by
543         four textures. 'backendTextureInfo' describes the planar arrangement, texture formats,
544         conversion to RGB, and origin of the textures. Separate 'textureFulfillProc' and
545         'textureReleaseProc' calls are made for each texture. Each texture has its own
546         PromiseImageTextureContext. If 'backendTextureInfo' is not valid then no release proc
547         calls are made. Otherwise, the calls will be made even on failure. 'textureContexts' has one
548         entry for each of the up to four textures, as indicated by 'backendTextureInfo'.
549 
550         Currently the mip mapped property of 'backendTextureInfo' is ignored. However, in the
551         near future it will be required that if it is kYes then textureFulfillProc must return
552         a mip mapped texture for each plane in order to successfully draw the image.
553 
554         @param gpuContextProxy     the thread-safe proxy of the gpu context. required.
555         @param backendTextureInfo  info about the promised yuva gpu texture
556         @param imageColorSpace     range of colors; may be nullptr
557         @param textureFulfillProc  function called to get actual gpu texture
558         @param textureReleaseProc  function called when texture can be deleted
559         @param textureContexts     state passed to textureFulfillProc and textureReleaseProc
560         @return                    created SkImage, or nullptr
561     */
562     static sk_sp<SkImage> MakePromiseYUVATexture(sk_sp<GrContextThreadSafeProxy> gpuContextProxy,
563                                                  const GrYUVABackendTextureInfo& backendTextureInfo,
564                                                  sk_sp<SkColorSpace> imageColorSpace,
565                                                  PromiseImageTextureFulfillProc textureFulfillProc,
566                                                  PromiseImageTextureReleaseProc textureReleaseProc,
567                                                  PromiseImageTextureContext textureContexts[]);
568 
569 #endif // defined(SK_GANESH)
570 
571 #if defined(SK_BUILD_FOR_ANDROID) && __ANDROID_API__ >= 26
572     /** (See Skia bug 7447)
573         Creates SkImage from Android hardware buffer.
574         Returned SkImage takes a reference on the buffer.
575 
576         Only available on Android, when __ANDROID_API__ is defined to be 26 or greater.
577 
578         @param hardwareBuffer  AHardwareBuffer Android hardware buffer
579         @param colorSpace      range of colors; may be nullptr
580         @return                created SkImage, or nullptr
581     */
582     static sk_sp<SkImage> MakeFromAHardwareBuffer(
583             AHardwareBuffer* hardwareBuffer,
584             SkAlphaType alphaType = kPremul_SkAlphaType);
585     static sk_sp<SkImage> MakeFromAHardwareBuffer(
586             AHardwareBuffer* hardwareBuffer,
587             SkAlphaType alphaType,
588             sk_sp<SkColorSpace> colorSpace,
589             GrSurfaceOrigin surfaceOrigin = kTopLeft_GrSurfaceOrigin);
590 
591     /** Creates SkImage from Android hardware buffer and uploads the data from the SkPixmap to it.
592         Returned SkImage takes a reference on the buffer.
593 
594         Only available on Android, when __ANDROID_API__ is defined to be 26 or greater.
595 
596         @param context         GPU context
597         @param pixmap          SkPixmap that contains data to be uploaded to the AHardwareBuffer
598         @param hardwareBuffer  AHardwareBuffer Android hardware buffer
599         @param surfaceOrigin   surface origin for resulting image
600         @return                created SkImage, or nullptr
601     */
602     static sk_sp<SkImage> MakeFromAHardwareBufferWithData(
603             GrDirectContext* context,
604             const SkPixmap& pixmap,
605             AHardwareBuffer* hardwareBuffer,
606             GrSurfaceOrigin surfaceOrigin = kTopLeft_GrSurfaceOrigin);
607 #endif
608 
609     /** Returns a SkImageInfo describing the width, height, color type, alpha type, and color space
610         of the SkImage.
611 
612         @return  image info of SkImage.
613     */
imageInfo()614     const SkImageInfo& imageInfo() const { return fInfo; }
615 
616     /** Returns pixel count in each row.
617 
618         @return  pixel width in SkImage
619     */
width()620     int width() const { return fInfo.width(); }
621 
622     /** Returns pixel row count.
623 
624         @return  pixel height in SkImage
625     */
height()626     int height() const { return fInfo.height(); }
627 
628     /** Returns SkISize { width(), height() }.
629 
630         @return  integral size of width() and height()
631     */
dimensions()632     SkISize dimensions() const { return SkISize::Make(fInfo.width(), fInfo.height()); }
633 
634     /** Returns SkIRect { 0, 0, width(), height() }.
635 
636         @return  integral rectangle from origin to width() and height()
637     */
bounds()638     SkIRect bounds() const { return SkIRect::MakeWH(fInfo.width(), fInfo.height()); }
639 
640     /** Returns value unique to image. SkImage contents cannot change after SkImage is
641         created. Any operation to create a new SkImage will receive generate a new
642         unique number.
643 
644         @return  unique identifier
645     */
uniqueID()646     uint32_t uniqueID() const { return fUniqueID; }
647 
648     /** Returns SkAlphaType.
649 
650         SkAlphaType returned was a parameter to an SkImage constructor,
651         or was parsed from encoded data.
652 
653         @return  SkAlphaType in SkImage
654 
655         example: https://fiddle.skia.org/c/@Image_alphaType
656     */
657     SkAlphaType alphaType() const;
658 
659     /** Returns SkColorType if known; otherwise, returns kUnknown_SkColorType.
660 
661         @return  SkColorType of SkImage
662 
663         example: https://fiddle.skia.org/c/@Image_colorType
664     */
665     SkColorType colorType() const;
666 
667     /** Returns SkColorSpace, the range of colors, associated with SkImage.  The
668         reference count of SkColorSpace is unchanged. The returned SkColorSpace is
669         immutable.
670 
671         SkColorSpace returned was passed to an SkImage constructor,
672         or was parsed from encoded data. SkColorSpace returned may be ignored when SkImage
673         is drawn, depending on the capabilities of the SkSurface receiving the drawing.
674 
675         @return  SkColorSpace in SkImage, or nullptr
676 
677         example: https://fiddle.skia.org/c/@Image_colorSpace
678     */
679     SkColorSpace* colorSpace() const;
680 
681     /** Returns a smart pointer to SkColorSpace, the range of colors, associated with
682         SkImage.  The smart pointer tracks the number of objects sharing this
683         SkColorSpace reference so the memory is released when the owners destruct.
684 
685         The returned SkColorSpace is immutable.
686 
687         SkColorSpace returned was passed to an SkImage constructor,
688         or was parsed from encoded data. SkColorSpace returned may be ignored when SkImage
689         is drawn, depending on the capabilities of the SkSurface receiving the drawing.
690 
691         @return  SkColorSpace in SkImage, or nullptr, wrapped in a smart pointer
692 
693         example: https://fiddle.skia.org/c/@Image_refColorSpace
694     */
695     sk_sp<SkColorSpace> refColorSpace() const;
696 
697     /** Returns true if SkImage pixels represent transparency only. If true, each pixel
698         is packed in 8 bits as defined by kAlpha_8_SkColorType.
699 
700         @return  true if pixels represent a transparency mask
701 
702         example: https://fiddle.skia.org/c/@Image_isAlphaOnly
703     */
704     bool isAlphaOnly() const;
705 
706     /** Returns true if pixels ignore their alpha value and are treated as fully opaque.
707 
708         @return  true if SkAlphaType is kOpaque_SkAlphaType
709     */
isOpaque()710     bool isOpaque() const { return SkAlphaTypeIsOpaque(this->alphaType()); }
711 
712     /**
713      *  Make a shader with the specified tiling and mipmap sampling.
714      */
715     sk_sp<SkShader> makeShader(SkTileMode tmx, SkTileMode tmy, const SkSamplingOptions&,
716                                const SkMatrix* localMatrix = nullptr) const;
717     sk_sp<SkShader> makeShader(SkTileMode tmx, SkTileMode tmy, const SkSamplingOptions& sampling,
718                                const SkMatrix& lm) const;
719     /** Defaults to clamp in both X and Y. */
720     sk_sp<SkShader> makeShader(const SkSamplingOptions& sampling, const SkMatrix& lm) const;
721     sk_sp<SkShader> makeShader(const SkSamplingOptions& sampling,
722                                const SkMatrix* lm = nullptr) const;
723 
724     /**
725      *  makeRawShader functions like makeShader, but for images that contain non-color data.
726      *  This includes images encoding things like normals, material properties (eg, roughness),
727      *  heightmaps, or any other purely mathematical data that happens to be stored in an image.
728      *  These types of images are useful with some programmable shaders (see: SkRuntimeEffect).
729      *
730      *  Raw image shaders work like regular image shaders (including filtering and tiling), with
731      *  a few major differences:
732      *    - No color space transformation is ever applied (the color space of the image is ignored).
733      *    - Images with an alpha type of kUnpremul are *not* automatically premultiplied.
734      *    - Bicubic filtering is not supported. If SkSamplingOptions::useCubic is true, these
735      *      factories will return nullptr.
736      */
737     sk_sp<SkShader> makeRawShader(SkTileMode tmx, SkTileMode tmy, const SkSamplingOptions&,
738                                   const SkMatrix* localMatrix = nullptr) const;
739     sk_sp<SkShader> makeRawShader(SkTileMode tmx, SkTileMode tmy, const SkSamplingOptions& sampling,
740                                   const SkMatrix& lm) const;
741     /** Defaults to clamp in both X and Y. */
742     sk_sp<SkShader> makeRawShader(const SkSamplingOptions& sampling, const SkMatrix& lm) const;
743     sk_sp<SkShader> makeRawShader(const SkSamplingOptions& sampling,
744                                   const SkMatrix* lm = nullptr) const;
745 
746     /** Copies SkImage pixel address, row bytes, and SkImageInfo to pixmap, if address
747         is available, and returns true. If pixel address is not available, return
748         false and leave pixmap unchanged.
749 
750         @param pixmap  storage for pixel state if pixels are readable; otherwise, ignored
751         @return        true if SkImage has direct access to pixels
752 
753         example: https://fiddle.skia.org/c/@Image_peekPixels
754     */
755     bool peekPixels(SkPixmap* pixmap) const;
756 
757     /** Returns true if the contents of SkImage was created on or uploaded to GPU memory,
758         and is available as a GPU texture.
759 
760         @return  true if SkImage is a GPU texture
761 
762         example: https://fiddle.skia.org/c/@Image_isTextureBacked
763     */
764     bool isTextureBacked() const;
765 
766     /** Returns an approximation of the amount of texture memory used by the image. Returns
767         zero if the image is not texture backed or if the texture has an external format.
768      */
769     size_t textureSize() const;
770 
771     /** Returns true if SkImage can be drawn on either raster surface or GPU surface.
772         If context is nullptr, tests if SkImage draws on raster surface;
773         otherwise, tests if SkImage draws on GPU surface associated with context.
774 
775         SkImage backed by GPU texture may become invalid if associated context is
776         invalid. lazy image may be invalid and may not draw to raster surface or
777         GPU surface or both.
778 
779         @param context  GPU context
780         @return         true if SkImage can be drawn
781 
782         example: https://fiddle.skia.org/c/@Image_isValid
783     */
784     bool isValid(GrRecordingContext* context) const;
785 
786 #if defined(SK_GANESH)
787     /** Flushes any pending uses of texture-backed images in the GPU backend. If the image is not
788         texture-backed (including promise texture images) or if the GrDirectContext does not
789         have the same context ID as the context backing the image then this is a no-op.
790 
791         If the image was not used in any non-culled draws in the current queue of work for the
792         passed GrDirectContext then this is a no-op unless the GrFlushInfo contains semaphores or
793         a finish proc. Those are respected even when the image has not been used.
794 
795         @param context  the context on which to flush pending usages of the image.
796         @param info     flush options
797      */
798     GrSemaphoresSubmitted flush(GrDirectContext* context, const GrFlushInfo& flushInfo) const;
799 
flush(GrDirectContext * context)800     void flush(GrDirectContext* context) const { this->flush(context, {}); }
801 
802     /** Version of flush() that uses a default GrFlushInfo. Also submits the flushed work to the
803         GPU.
804     */
805     void flushAndSubmit(GrDirectContext*) const;
806 
807     /** Retrieves the back-end texture. If SkImage has no back-end texture, an invalid
808         object is returned. Call GrBackendTexture::isValid to determine if the result
809         is valid.
810 
811         If flushPendingGrContextIO is true, completes deferred I/O operations.
812 
813         If origin in not nullptr, copies location of content drawn into SkImage.
814 
815         @param flushPendingGrContextIO  flag to flush outstanding requests
816         @return                         back-end API texture handle; invalid on failure
817     */
818     GrBackendTexture getBackendTexture(bool flushPendingGrContextIO,
819                                        GrSurfaceOrigin* origin = nullptr) const;
820 #endif // defined(SK_GANESH)
821 
822     /** \enum SkImage::CachingHint
823         CachingHint selects whether Skia may internally cache SkBitmap generated by
824         decoding SkImage, or by copying SkImage from GPU to CPU. The default behavior
825         allows caching SkBitmap.
826 
827         Choose kDisallow_CachingHint if SkImage pixels are to be used only once, or
828         if SkImage pixels reside in a cache outside of Skia, or to reduce memory pressure.
829 
830         Choosing kAllow_CachingHint does not ensure that pixels will be cached.
831         SkImage pixels may not be cached if memory requirements are too large or
832         pixels are not accessible.
833     */
834     enum CachingHint {
835         kAllow_CachingHint,    //!< allows internally caching decoded and copied pixels
836         kDisallow_CachingHint, //!< disallows internally caching decoded and copied pixels
837     };
838 
839     /** Copies SkRect of pixels from SkImage to dstPixels. Copy starts at offset (srcX, srcY),
840         and does not exceed SkImage (width(), height()).
841 
842         dstInfo specifies width, height, SkColorType, SkAlphaType, and SkColorSpace of
843         destination. dstRowBytes specifies the gap from one destination row to the next.
844         Returns true if pixels are copied. Returns false if:
845         - dstInfo.addr() equals nullptr
846         - dstRowBytes is less than dstInfo.minRowBytes()
847         - SkPixelRef is nullptr
848 
849         Pixels are copied only if pixel conversion is possible. If SkImage SkColorType is
850         kGray_8_SkColorType, or kAlpha_8_SkColorType; dstInfo.colorType() must match.
851         If SkImage SkColorType is kGray_8_SkColorType, dstInfo.colorSpace() must match.
852         If SkImage SkAlphaType is kOpaque_SkAlphaType, dstInfo.alphaType() must
853         match. If SkImage SkColorSpace is nullptr, dstInfo.colorSpace() must match. Returns
854         false if pixel conversion is not possible.
855 
856         srcX and srcY may be negative to copy only top or left of source. Returns
857         false if width() or height() is zero or negative.
858         Returns false if abs(srcX) >= Image width(), or if abs(srcY) >= Image height().
859 
860         If cachingHint is kAllow_CachingHint, pixels may be retained locally.
861         If cachingHint is kDisallow_CachingHint, pixels are not added to the local cache.
862 
863         @param context      the GrDirectContext in play, if it exists
864         @param dstInfo      destination width, height, SkColorType, SkAlphaType, SkColorSpace
865         @param dstPixels    destination pixel storage
866         @param dstRowBytes  destination row length
867         @param srcX         column index whose absolute value is less than width()
868         @param srcY         row index whose absolute value is less than height()
869         @param cachingHint  whether the pixels should be cached locally
870         @return             true if pixels are copied to dstPixels
871     */
872     bool readPixels(GrDirectContext* context,
873                     const SkImageInfo& dstInfo,
874                     void* dstPixels,
875                     size_t dstRowBytes,
876                     int srcX, int srcY,
877                     CachingHint cachingHint = kAllow_CachingHint) const;
878 
879     /** Copies a SkRect of pixels from SkImage to dst. Copy starts at (srcX, srcY), and
880         does not exceed SkImage (width(), height()).
881 
882         dst specifies width, height, SkColorType, SkAlphaType, SkColorSpace, pixel storage,
883         and row bytes of destination. dst.rowBytes() specifics the gap from one destination
884         row to the next. Returns true if pixels are copied. Returns false if:
885         - dst pixel storage equals nullptr
886         - dst.rowBytes is less than SkImageInfo::minRowBytes
887         - SkPixelRef is nullptr
888 
889         Pixels are copied only if pixel conversion is possible. If SkImage SkColorType is
890         kGray_8_SkColorType, or kAlpha_8_SkColorType; dst.colorType() must match.
891         If SkImage SkColorType is kGray_8_SkColorType, dst.colorSpace() must match.
892         If SkImage SkAlphaType is kOpaque_SkAlphaType, dst.alphaType() must
893         match. If SkImage SkColorSpace is nullptr, dst.colorSpace() must match. Returns
894         false if pixel conversion is not possible.
895 
896         srcX and srcY may be negative to copy only top or left of source. Returns
897         false if width() or height() is zero or negative.
898         Returns false if abs(srcX) >= Image width(), or if abs(srcY) >= Image height().
899 
900         If cachingHint is kAllow_CachingHint, pixels may be retained locally.
901         If cachingHint is kDisallow_CachingHint, pixels are not added to the local cache.
902 
903         @param context      the GrDirectContext in play, if it exists
904         @param dst          destination SkPixmap: SkImageInfo, pixels, row bytes
905         @param srcX         column index whose absolute value is less than width()
906         @param srcY         row index whose absolute value is less than height()
907         @param cachingHint  whether the pixels should be cached locallyZ
908         @return             true if pixels are copied to dst
909     */
910     bool readPixels(GrDirectContext* context,
911                     const SkPixmap& dst,
912                     int srcX,
913                     int srcY,
914                     CachingHint cachingHint = kAllow_CachingHint) const;
915 
916 #ifndef SK_IMAGE_READ_PIXELS_DISABLE_LEGACY_API
917     /** Deprecated. Use the variants that accept a GrDirectContext. */
918     bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
919                     int srcX, int srcY, CachingHint cachingHint = kAllow_CachingHint) const;
920     bool readPixels(const SkPixmap& dst, int srcX, int srcY,
921                     CachingHint cachingHint = kAllow_CachingHint) const;
922 #endif
923 
924     /** The result from asyncRescaleAndReadPixels() or asyncRescaleAndReadPixelsYUV420(). */
925     class AsyncReadResult {
926     public:
927         AsyncReadResult(const AsyncReadResult&) = delete;
928         AsyncReadResult(AsyncReadResult&&) = delete;
929         AsyncReadResult& operator=(const AsyncReadResult&) = delete;
930         AsyncReadResult& operator=(AsyncReadResult&&) = delete;
931 
932         virtual ~AsyncReadResult() = default;
933         virtual int count() const = 0;
934         virtual const void* data(int i) const = 0;
935         virtual size_t rowBytes(int i) const = 0;
936 
937     protected:
938         AsyncReadResult() = default;
939     };
940 
941     /** Client-provided context that is passed to client-provided ReadPixelsContext. */
942     using ReadPixelsContext = void*;
943 
944     /**  Client-provided callback to asyncRescaleAndReadPixels() or
945          asyncRescaleAndReadPixelsYUV420() that is called when read result is ready or on failure.
946      */
947     using ReadPixelsCallback = void(ReadPixelsContext, std::unique_ptr<const AsyncReadResult>);
948 
949     enum class RescaleGamma : bool { kSrc, kLinear };
950 
951     enum class RescaleMode {
952         kNearest,
953         kLinear,
954         kRepeatedLinear,
955         kRepeatedCubic,
956     };
957 
958     /** Makes image pixel data available to caller, possibly asynchronously. It can also rescale
959         the image pixels.
960 
961         Currently asynchronous reads are only supported on the GPU backend and only when the
962         underlying 3D API supports transfer buffers and CPU/GPU synchronization primitives. In all
963         other cases this operates synchronously.
964 
965         Data is read from the source sub-rectangle, is optionally converted to a linear gamma, is
966         rescaled to the size indicated by 'info', is then converted to the color space, color type,
967         and alpha type of 'info'. A 'srcRect' that is not contained by the bounds of the image
968         causes failure.
969 
970         When the pixel data is ready the caller's ReadPixelsCallback is called with a
971         AsyncReadResult containing pixel data in the requested color type, alpha type, and color
972         space. The AsyncReadResult will have count() == 1. Upon failure the callback is called with
973         nullptr for AsyncReadResult. For a GPU image this flushes work but a submit must occur to
974         guarantee a finite time before the callback is called.
975 
976         The data is valid for the lifetime of AsyncReadResult with the exception that if the SkImage
977         is GPU-backed the data is immediately invalidated if the context is abandoned or
978         destroyed.
979 
980         @param info            info of the requested pixels
981         @param srcRect         subrectangle of image to read
982         @param rescaleGamma    controls whether rescaling is done in the image's gamma or whether
983                                the source data is transformed to a linear gamma before rescaling.
984         @param rescaleMode     controls the technique (and cost) of the rescaling
985         @param callback        function to call with result of the read
986         @param context         passed to callback
987     */
988     void asyncRescaleAndReadPixels(const SkImageInfo& info,
989                                    const SkIRect& srcRect,
990                                    RescaleGamma rescaleGamma,
991                                    RescaleMode rescaleMode,
992                                    ReadPixelsCallback callback,
993                                    ReadPixelsContext context) const;
994 
995     /**
996         Similar to asyncRescaleAndReadPixels but performs an additional conversion to YUV. The
997         RGB->YUV conversion is controlled by 'yuvColorSpace'. The YUV data is returned as three
998         planes ordered y, u, v. The u and v planes are half the width and height of the resized
999         rectangle. The y, u, and v values are single bytes. Currently this fails if 'dstSize'
1000         width and height are not even. A 'srcRect' that is not contained by the bounds of the
1001         image causes failure.
1002 
1003         When the pixel data is ready the caller's ReadPixelsCallback is called with a
1004         AsyncReadResult containing the planar data. The AsyncReadResult will have count() == 3.
1005         Upon failure the callback is called with nullptr for AsyncReadResult. For a GPU image this
1006         flushes work but a submit must occur to guarantee a finite time before the callback is
1007         called.
1008 
1009         The data is valid for the lifetime of AsyncReadResult with the exception that if the SkImage
1010         is GPU-backed the data is immediately invalidated if the context is abandoned or
1011         destroyed.
1012 
1013         @param yuvColorSpace  The transformation from RGB to YUV. Applied to the resized image
1014                               after it is converted to dstColorSpace.
1015         @param dstColorSpace  The color space to convert the resized image to, after rescaling.
1016         @param srcRect        The portion of the image to rescale and convert to YUV planes.
1017         @param dstSize        The size to rescale srcRect to
1018         @param rescaleGamma   controls whether rescaling is done in the image's gamma or whether
1019                               the source data is transformed to a linear gamma before rescaling.
1020         @param rescaleMode    controls the technique (and cost) of the rescaling
1021         @param callback       function to call with the planar read result
1022         @param context        passed to callback
1023      */
1024     void asyncRescaleAndReadPixelsYUV420(SkYUVColorSpace yuvColorSpace,
1025                                          sk_sp<SkColorSpace> dstColorSpace,
1026                                          const SkIRect& srcRect,
1027                                          const SkISize& dstSize,
1028                                          RescaleGamma rescaleGamma,
1029                                          RescaleMode rescaleMode,
1030                                          ReadPixelsCallback callback,
1031                                          ReadPixelsContext context) const;
1032 
1033     /** Copies SkImage to dst, scaling pixels to fit dst.width() and dst.height(), and
1034         converting pixels to match dst.colorType() and dst.alphaType(). Returns true if
1035         pixels are copied. Returns false if dst.addr() is nullptr, or dst.rowBytes() is
1036         less than dst SkImageInfo::minRowBytes.
1037 
1038         Pixels are copied only if pixel conversion is possible. If SkImage SkColorType is
1039         kGray_8_SkColorType, or kAlpha_8_SkColorType; dst.colorType() must match.
1040         If SkImage SkColorType is kGray_8_SkColorType, dst.colorSpace() must match.
1041         If SkImage SkAlphaType is kOpaque_SkAlphaType, dst.alphaType() must
1042         match. If SkImage SkColorSpace is nullptr, dst.colorSpace() must match. Returns
1043         false if pixel conversion is not possible.
1044 
1045         If cachingHint is kAllow_CachingHint, pixels may be retained locally.
1046         If cachingHint is kDisallow_CachingHint, pixels are not added to the local cache.
1047 
1048         @param dst            destination SkPixmap: SkImageInfo, pixels, row bytes
1049         @return               true if pixels are scaled to fit dst
1050     */
1051     bool scalePixels(const SkPixmap& dst, const SkSamplingOptions&,
1052                      CachingHint cachingHint = kAllow_CachingHint) const;
1053 
1054     /** Encodes SkImage pixels, returning result as SkData.
1055 
1056         Returns nullptr if encoding fails, or if encodedImageFormat is not supported.
1057 
1058         SkImage encoding in a format requires both building with one or more of:
1059         SK_ENCODE_JPEG, SK_ENCODE_PNG, SK_ENCODE_WEBP; and platform support
1060         for the encoded format.
1061 
1062         If SK_BUILD_FOR_MAC or SK_BUILD_FOR_IOS is defined, encodedImageFormat can
1063         additionally be one of: SkEncodedImageFormat::kICO, SkEncodedImageFormat::kBMP,
1064         SkEncodedImageFormat::kGIF.
1065 
1066         quality is a platform and format specific metric trading off size and encoding
1067         error. When used, quality equaling 100 encodes with the least error. quality may
1068         be ignored by the encoder.
1069 
1070         @param encodedImageFormat  one of: SkEncodedImageFormat::kJPEG, SkEncodedImageFormat::kPNG,
1071                                    SkEncodedImageFormat::kWEBP
1072         @param quality             encoder specific metric with 100 equaling best
1073         @return                    encoded SkImage, or nullptr
1074 
1075         example: https://fiddle.skia.org/c/@Image_encodeToData
1076     */
1077     sk_sp<SkData> encodeToData(SkEncodedImageFormat encodedImageFormat, int quality) const;
1078 
1079     /** Encodes SkImage pixels, returning result as SkData. Returns existing encoded data
1080         if present; otherwise, SkImage is encoded with SkEncodedImageFormat::kPNG. Skia
1081         must be built with SK_ENCODE_PNG to encode SkImage.
1082 
1083         Returns nullptr if existing encoded data is missing or invalid, and
1084         encoding fails.
1085 
1086         @return  encoded SkImage, or nullptr
1087 
1088         example: https://fiddle.skia.org/c/@Image_encodeToData_2
1089     */
1090     sk_sp<SkData> encodeToData() const;
1091 
1092     /** Returns encoded SkImage pixels as SkData, if SkImage was created from supported
1093         encoded stream format. Platform support for formats vary and may require building
1094         with one or more of: SK_ENCODE_JPEG, SK_ENCODE_PNG, SK_ENCODE_WEBP.
1095 
1096         Returns nullptr if SkImage contents are not encoded.
1097 
1098         @return  encoded SkImage, or nullptr
1099 
1100         example: https://fiddle.skia.org/c/@Image_refEncodedData
1101     */
1102     sk_sp<SkData> refEncodedData() const;
1103 
1104     /** Returns subset of this image.
1105 
1106         Returns nullptr if any of the following are true:
1107           - Subset is empty
1108           - Subset is not contained inside the image's bounds
1109           - Pixels in the image could not be read or copied
1110 
1111         If this image is texture-backed, the context parameter is required and must match the
1112         context of the source image. If the context parameter is provided, and the image is
1113         raster-backed, the subset will be converted to texture-backed.
1114 
1115         @param subset  bounds of returned SkImage
1116         @param context the GrDirectContext in play, if it exists
1117         @return        the subsetted image, or nullptr
1118 
1119         example: https://fiddle.skia.org/c/@Image_makeSubset
1120     */
1121     sk_sp<SkImage> makeSubset(const SkIRect& subset, GrDirectContext* direct = nullptr) const;
1122 
1123     /**
1124      *  Returns true if the image has mipmap levels.
1125      */
1126     bool hasMipmaps() const;
1127 
1128     /**
1129      *  Returns an image with the same "base" pixels as the this image, but with mipmap levels
1130      *  automatically generated and attached.
1131      */
1132     sk_sp<SkImage> withDefaultMipmaps() const;
1133 
1134 #if defined(SK_GANESH)
1135     /** Returns SkImage backed by GPU texture associated with context. Returned SkImage is
1136         compatible with SkSurface created with dstColorSpace. The returned SkImage respects
1137         mipmapped setting; if mipmapped equals GrMipmapped::kYes, the backing texture
1138         allocates mip map levels.
1139 
1140         The mipmapped parameter is effectively treated as kNo if MIP maps are not supported by the
1141         GPU.
1142 
1143         Returns original SkImage if the image is already texture-backed, the context matches, and
1144         mipmapped is compatible with the backing GPU texture. skgpu::Budgeted is ignored in this
1145        case.
1146 
1147         Returns nullptr if context is nullptr, or if SkImage was created with another
1148         GrDirectContext.
1149 
1150         @param GrDirectContext the GrDirectContext in play, if it exists
1151         @param GrMipmapped     whether created SkImage texture must allocate mip map levels
1152         @param skgpu::Budgeted      whether to count a newly created texture for the returned image
1153                                counts against the context's budget.
1154         @return                created SkImage, or nullptr
1155     */
1156     sk_sp<SkImage> makeTextureImage(GrDirectContext*,
1157                                     GrMipmapped = GrMipmapped::kNo,
1158                                     skgpu::Budgeted = skgpu::Budgeted::kYes) const;
1159 #endif // defined(SK_GANESH)
1160 
1161 #if defined(SK_GRAPHITE)
1162 
1163     // Passed to both fulfill and imageRelease
1164     using GraphitePromiseImageContext = void*;
1165     // Returned from fulfill and passed into textureRelease
1166     using GraphitePromiseTextureReleaseContext = void*;
1167 
1168     using GraphitePromiseImageFulfillProc =
1169             std::tuple<skgpu::graphite::BackendTexture, GraphitePromiseTextureReleaseContext>
1170             (*)(GraphitePromiseImageContext);
1171     using GraphitePromiseImageReleaseProc = void (*)(GraphitePromiseImageContext);
1172     using GraphitePromiseTextureReleaseProc = void (*)(GraphitePromiseTextureReleaseContext);
1173 
1174     /** Create a new SkImage that is very similar to an SkImage created by
1175         MakeGraphiteFromBackendTexture. The difference is that the caller need not have created the
1176         backend texture nor populated it with data when creating the image. Instead of passing a
1177         BackendTexture to the factory the client supplies a description of the texture consisting
1178         of dimensions, TextureInfo, SkColorInfo and Volatility.
1179 
1180         In general, 'fulfill' must return a BackendTexture that matches the properties
1181         provided at SkImage creation time. The BackendTexture must refer to a valid existing
1182         texture in the backend API context/device, and already be populated with data.
1183         The texture cannot be deleted until 'textureRelease' is called. 'textureRelease' will
1184         be called with the textureReleaseContext returned by 'fulfill'.
1185 
1186         Wrt when and how often the fulfill, imageRelease, and textureRelease callbacks will
1187         be called:
1188 
1189         For non-volatile promise images, 'fulfill' will be called at Context::insertRecording
1190         time. Regardless of whether 'fulfill' succeeded or failed, 'imageRelease' will always be
1191         called only once - when Skia will no longer try calling 'fulfill' to get a backend
1192         texture. If 'fulfill' failed (i.e., it didn't return a valid backend texture) then
1193         'textureRelease' will never be called. If 'fulfill' was successful then
1194         'textureRelease' will be called only once when the GPU is done with the contents of the
1195         promise image. This will usually occur during a Context::submit call but it could occur
1196         earlier due to error conditions. 'fulfill' can be called multiple times if the promise
1197         image is used in multiple recordings. If 'fulfill' fails, the insertRecording itself will
1198         fail. Subsequent insertRecording calls (with Recordings that use the promise image) will
1199         keep calling 'fulfill' until it succeeds.
1200 
1201         For volatile promise images, 'fulfill' will be called each time the Recording is inserted
1202         into a Context. Regardless of whether 'fulfill' succeeded or failed, 'imageRelease'
1203         will always be called only once just like the non-volatile case. If 'fulfill' fails at
1204         insertRecording-time, 'textureRelease' will never be called. If 'fulfill' was successful
1205         then a 'textureRelease' matching that 'fulfill' will be called when the GPU is done with
1206         the contents of the promise image. This will usually occur during a Context::submit call
1207         but it could occur earlier due to error conditions.
1208 
1209         @param recorder       the recorder that will capture the commands creating the image
1210         @param dimensions     width & height of promised gpu texture
1211         @param textureInfo    structural information for the promised gpu texture
1212         @param colorInfo      color type, alpha type and colorSpace information for the image
1213         @param isVolatile     volatility of the promise image
1214         @param fulfill        function called to get the actual backend texture
1215         @param imageRelease   function called when any image-centric data can be deleted
1216         @param textureRelease function called when the backend texture can be deleted
1217         @param imageContext   state passed to fulfill and imageRelease
1218         @return               created SkImage, or nullptr
1219     */
1220     static sk_sp<SkImage> MakeGraphitePromiseTexture(skgpu::graphite::Recorder*,
1221                                                      SkISize dimensions,
1222                                                      const skgpu::graphite::TextureInfo&,
1223                                                      const SkColorInfo&,
1224                                                      skgpu::graphite::Volatile,
1225                                                      GraphitePromiseImageFulfillProc,
1226                                                      GraphitePromiseImageReleaseProc,
1227                                                      GraphitePromiseTextureReleaseProc,
1228                                                      GraphitePromiseImageContext);
1229 
1230     /** Creates an SkImage from a GPU texture associated with the recorder.
1231 
1232         SkImage is returned if the format of backendTexture is recognized and supported.
1233         Recognized formats vary by GPU back-end.
1234 
1235         @param recorder            The recorder
1236         @param backendTexture      texture residing on GPU
1237         @param colorSpace          This describes the color space of this image's contents, as
1238                                    seen after sampling. In general, if the format of the backend
1239                                    texture is SRGB, some linear colorSpace should be supplied
1240                                    (e.g., SkColorSpace::MakeSRGBLinear()). If the format of the
1241                                    backend texture is linear, then the colorSpace should include
1242                                    a description of the transfer function as
1243                                    well (e.g., SkColorSpace::MakeSRGB()).
1244         @return                    created SkImage, or nullptr
1245     */
1246     static sk_sp<SkImage> MakeGraphiteFromBackendTexture(skgpu::graphite::Recorder*,
1247                                                          const skgpu::graphite::BackendTexture&,
1248                                                          SkColorType colorType,
1249                                                          SkAlphaType alphaType,
1250                                                          sk_sp<SkColorSpace> colorSpace);
1251 
1252     struct RequiredImageProperties {
1253         skgpu::Mipmapped fMipmapped;
1254     };
1255 
1256     /** Graphite version of makeTextureImage.
1257 
1258         Returns an SkImage backed by a Graphite texture, using the provided Recorder for creation
1259         and uploads if necessary. The returned SkImage respects the required image properties'
1260         mipmap setting for non-Graphite SkImages; i.e., if mipmapping is required, the backing
1261         Graphite texture will have allocated mip map levels.
1262 
1263         It is assumed that MIP maps are always supported by the GPU.
1264 
1265         Returns original SkImage if the image is already Graphite-backed and the required mipmapping
1266         is compatible with the backing Graphite texture. If the required mipmapping is not
1267         compatible, nullptr will be returned.
1268 
1269         Returns nullptr if no Recorder is provided, or if SkImage was created with another
1270         Recorder and work on that Recorder has not been submitted.
1271 
1272         @param Recorder                 the Recorder to use for storing commands
1273         @param RequiredImageProperties  properties the returned SkImage must possess (e.g.,
1274                                         mipmaps)
1275         @return                         created SkImage, or nullptr
1276     */
1277     sk_sp<SkImage> makeTextureImage(skgpu::graphite::Recorder*,
1278                                     RequiredImageProperties = {}) const;
1279 
1280     /** Returns subset of this image.
1281 
1282         Returns nullptr if any of the following are true:
1283           - Subset is empty
1284           - Subset is not contained inside the image's bounds
1285           - Pixels in the image could not be read or copied
1286 
1287         If this image is texture-backed, the recorder parameter is required.
1288         If the recorder parameter is provided, and the image is raster-backed, the subset will
1289         be converted to texture-backed.
1290 
1291         @param subset                   bounds of returned SkImage
1292         @param recorder                 the recorder in which to create the new image
1293         @param RequiredImageProperties  properties the returned SkImage must possess (e.g.,
1294                                         mipmaps)
1295         @return                         the subsetted image, or nullptr
1296     */
1297     sk_sp<SkImage> makeSubset(const SkIRect& subset,
1298                               skgpu::graphite::Recorder*,
1299                               RequiredImageProperties = {}) const;
1300 
1301     /** Creates SkImage in target SkColorSpace.
1302         Returns nullptr if SkImage could not be created.
1303 
1304         Returns original SkImage if it is in target SkColorSpace.
1305         Otherwise, converts pixels from SkImage SkColorSpace to target SkColorSpace.
1306         If SkImage colorSpace() returns nullptr, SkImage SkColorSpace is assumed to be sRGB.
1307 
1308         If this image is graphite-backed, the recorder parameter is required.
1309 
1310         @param targetColorSpace         SkColorSpace describing color range of returned SkImage
1311         @param recorder                 The Recorder in which to create the new image
1312         @param RequiredImageProperties  properties the returned SkImage must possess (e.g.,
1313                                         mipmaps)
1314         @return                         created SkImage in target SkColorSpace
1315     */
1316     sk_sp<SkImage> makeColorSpace(sk_sp<SkColorSpace> targetColorSpace,
1317                                   skgpu::graphite::Recorder*,
1318                                   RequiredImageProperties = {}) const;
1319 
1320     /** Experimental.
1321         Creates SkImage in target SkColorType and SkColorSpace.
1322         Returns nullptr if SkImage could not be created.
1323 
1324         Returns original SkImage if it is in target SkColorType and SkColorSpace.
1325 
1326         If this image is graphite-backed, the recorder parameter is required.
1327 
1328         @param targetColorType          SkColorType of returned SkImage
1329         @param targetColorSpace         SkColorSpace of returned SkImage
1330         @param recorder                 The Recorder in which to create the new image
1331         @param RequiredImageProperties  properties the returned SkImage must possess (e.g.,
1332                                         mipmaps)
1333         @return                         created SkImage in target SkColorType and SkColorSpace
1334     */
1335     sk_sp<SkImage> makeColorTypeAndColorSpace(SkColorType targetColorType,
1336                                               sk_sp<SkColorSpace> targetColorSpace,
1337                                               skgpu::graphite::Recorder*,
1338                                               RequiredImageProperties = {}) const;
1339 
1340 #endif // SK_GRAPHITE
1341 
1342     /** Returns raster image or lazy image. Copies SkImage backed by GPU texture into
1343         CPU memory if needed. Returns original SkImage if decoded in raster bitmap,
1344         or if encoded in a stream.
1345 
1346         Returns nullptr if backed by GPU texture and copy fails.
1347 
1348         @return  raster image, lazy image, or nullptr
1349 
1350         example: https://fiddle.skia.org/c/@Image_makeNonTextureImage
1351     */
1352     sk_sp<SkImage> makeNonTextureImage() const;
1353 
1354     /** Returns raster image. Copies SkImage backed by GPU texture into CPU memory,
1355         or decodes SkImage from lazy image. Returns original SkImage if decoded in
1356         raster bitmap.
1357 
1358         Returns nullptr if copy, decode, or pixel read fails.
1359 
1360         If cachingHint is kAllow_CachingHint, pixels may be retained locally.
1361         If cachingHint is kDisallow_CachingHint, pixels are not added to the local cache.
1362 
1363         @return  raster image, or nullptr
1364 
1365         example: https://fiddle.skia.org/c/@Image_makeRasterImage
1366     */
1367     sk_sp<SkImage> makeRasterImage(CachingHint cachingHint = kDisallow_CachingHint) const;
1368 
1369     /** Creates filtered SkImage. filter processes original SkImage, potentially changing
1370         color, position, and size. subset is the bounds of original SkImage processed
1371         by filter. clipBounds is the expected bounds of the filtered SkImage. outSubset
1372         is required storage for the actual bounds of the filtered SkImage. offset is
1373         required storage for translation of returned SkImage.
1374 
1375         Returns nullptr if SkImage could not be created or if the recording context provided doesn't
1376         match the GPU context in which the image was created. If nullptr is returned, outSubset
1377         and offset are undefined.
1378 
1379         Useful for animation of SkImageFilter that varies size from frame to frame.
1380         Returned SkImage is created larger than required by filter so that GPU texture
1381         can be reused with different sized effects. outSubset describes the valid bounds
1382         of GPU texture returned. offset translates the returned SkImage to keep subsequent
1383         animation frames aligned with respect to each other.
1384 
1385         @param context     the GrRecordingContext in play - if it exists
1386         @param filter      how SkImage is sampled when transformed
1387         @param subset      bounds of SkImage processed by filter
1388         @param clipBounds  expected bounds of filtered SkImage
1389         @param outSubset   storage for returned SkImage bounds
1390         @param offset      storage for returned SkImage translation
1391         @return            filtered SkImage, or nullptr
1392     */
1393     sk_sp<SkImage> makeWithFilter(GrRecordingContext* context,
1394                                   const SkImageFilter* filter, const SkIRect& subset,
1395                                   const SkIRect& clipBounds, SkIRect* outSubset,
1396                                   SkIPoint* offset) const;
1397 
1398     /** Defines a callback function, taking one parameter of type GrBackendTexture with
1399         no return value. Function is called when back-end texture is to be released.
1400     */
1401     typedef std::function<void(GrBackendTexture)> BackendTextureReleaseProc;
1402 
1403 #if defined(SK_GANESH)
1404     /** Creates a GrBackendTexture from the provided SkImage. Returns true and
1405         stores result in backendTexture and backendTextureReleaseProc if
1406         texture is created; otherwise, returns false and leaves
1407         backendTexture and backendTextureReleaseProc unmodified.
1408 
1409         Call backendTextureReleaseProc after deleting backendTexture.
1410         backendTextureReleaseProc cleans up auxiliary data related to returned
1411         backendTexture. The caller must delete returned backendTexture after use.
1412 
1413         If SkImage is both texture backed and singly referenced, image is returned in
1414         backendTexture without conversion or making a copy. SkImage is singly referenced
1415         if its was transferred solely using std::move().
1416 
1417         If SkImage is not texture backed, returns texture with SkImage contents.
1418 
1419         @param context                    GPU context
1420         @param image                      SkImage used for texture
1421         @param backendTexture             storage for back-end texture
1422         @param backendTextureReleaseProc  storage for clean up function
1423         @return                           true if back-end texture was created
1424     */
1425     static bool MakeBackendTextureFromSkImage(GrDirectContext* context,
1426                                               sk_sp<SkImage> image,
1427                                               GrBackendTexture* backendTexture,
1428                                               BackendTextureReleaseProc* backendTextureReleaseProc);
1429 #endif
1430     /** Deprecated.
1431      */
1432     enum LegacyBitmapMode {
1433         kRO_LegacyBitmapMode, //!< returned bitmap is read-only and immutable
1434     };
1435 
1436     /** Deprecated.
1437         Creates raster SkBitmap with same pixels as SkImage. If legacyBitmapMode is
1438         kRO_LegacyBitmapMode, returned bitmap is read-only and immutable.
1439         Returns true if SkBitmap is stored in bitmap. Returns false and resets bitmap if
1440         SkBitmap write did not succeed.
1441 
1442         @param bitmap            storage for legacy SkBitmap
1443         @param legacyBitmapMode  bitmap is read-only and immutable
1444         @return                  true if SkBitmap was created
1445     */
1446     bool asLegacyBitmap(SkBitmap* bitmap,
1447                         LegacyBitmapMode legacyBitmapMode = kRO_LegacyBitmapMode) const;
1448 
1449     /** Returns true if SkImage is backed by an image-generator or other service that creates
1450         and caches its pixels or texture on-demand.
1451 
1452         @return  true if SkImage is created as needed
1453 
1454         example: https://fiddle.skia.org/c/@Image_isLazyGenerated_a
1455         example: https://fiddle.skia.org/c/@Image_isLazyGenerated_b
1456     */
1457     bool isLazyGenerated() const;
1458 
1459     /** Creates SkImage in target SkColorSpace.
1460         Returns nullptr if SkImage could not be created.
1461 
1462         Returns original SkImage if it is in target SkColorSpace.
1463         Otherwise, converts pixels from SkImage SkColorSpace to target SkColorSpace.
1464         If SkImage colorSpace() returns nullptr, SkImage SkColorSpace is assumed to be sRGB.
1465 
1466         If this image is texture-backed, the context parameter is required and must match the
1467         context of the source image.
1468 
1469         @param target  SkColorSpace describing color range of returned SkImage
1470         @param direct  The GrDirectContext in play, if it exists
1471         @return        created SkImage in target SkColorSpace
1472 
1473         example: https://fiddle.skia.org/c/@Image_makeColorSpace
1474     */
1475     sk_sp<SkImage> makeColorSpace(sk_sp<SkColorSpace> target,
1476                                   GrDirectContext* direct = nullptr) const;
1477 
1478     /** Experimental.
1479         Creates SkImage in target SkColorType and SkColorSpace.
1480         Returns nullptr if SkImage could not be created.
1481 
1482         Returns original SkImage if it is in target SkColorType and SkColorSpace.
1483 
1484         If this image is texture-backed, the context parameter is required and must match the
1485         context of the source image.
1486 
1487         @param targetColorType  SkColorType of returned SkImage
1488         @param targetColorSpace SkColorSpace of returned SkImage
1489         @param direct           The GrDirectContext in play, if it exists
1490         @return                 created SkImage in target SkColorType and SkColorSpace
1491     */
1492     sk_sp<SkImage> makeColorTypeAndColorSpace(SkColorType targetColorType,
1493                                               sk_sp<SkColorSpace> targetColorSpace,
1494                                               GrDirectContext* direct = nullptr) const;
1495 
1496     /** Creates a new SkImage identical to this one, but with a different SkColorSpace.
1497         This does not convert the underlying pixel data, so the resulting image will draw
1498         differently.
1499     */
1500     sk_sp<SkImage> reinterpretColorSpace(sk_sp<SkColorSpace> newColorSpace) const;
1501 
1502 private:
1503     SkImage(const SkImageInfo& info, uint32_t uniqueID);
1504 
1505     friend class SkBitmap;
1506     friend class SkImage_Base;   // for private ctor
1507     friend class SkImage_Raster; // for withMipmaps
1508     friend class SkMipmapBuilder;
1509 
1510     SkImageInfo     fInfo;
1511     const uint32_t  fUniqueID;
1512 
1513     sk_sp<SkImage> withMipmaps(sk_sp<SkMipmap>) const;
1514 
1515     using INHERITED = SkRefCnt;
1516 };
1517 
1518 #endif
1519