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