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