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