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/SkRefCnt.h" 14 #include "include/core/SkSamplingOptions.h" 15 #include "include/core/SkScalar.h" 16 #include "include/core/SkShader.h" 17 #include "include/core/SkTileMode.h" 18 #include "include/private/SkTOptional.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 * If alphaType is nullopt, the image's alpha type will be chosen automatically based on the 171 * image format. Transparent images will default to kPremul_SkAlphaType. If alphaType contains 172 * kPremul_SkAlphaType or kUnpremul_SkAlphaType, that alpha type will be used. Forcing opaque 173 * (passing kOpaque_SkAlphaType) is not allowed, and will return nullptr. 174 * 175 * This is similar to DecodeTo[Raster,Texture], but this method will attempt to defer the 176 * actual decode, while the DecodeTo... method explicitly decode and allocate the backend 177 * when the call is made. 178 * 179 * If the encoded format is not supported, nullptr is returned. 180 * 181 * @param encoded the 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 std::optional<SkAlphaType> alphaType = std::nullopt); 188 189 /* 190 * Experimental: 191 * Skia | GL_COMPRESSED_* | MTLPixelFormat* | VK_FORMAT_*_BLOCK 192 * -------------------------------------------------------------------------------------- 193 * kETC2_RGB8_UNORM | ETC1_RGB8 | ETC2_RGB8 (iOS-only) | ETC2_R8G8B8_UNORM 194 * | RGB8_ETC2 | | 195 * -------------------------------------------------------------------------------------- 196 * kBC1_RGB8_UNORM | RGB_S3TC_DXT1_EXT | N/A | BC1_RGB_UNORM 197 * -------------------------------------------------------------------------------------- 198 * kBC1_RGBA8_UNORM | RGBA_S3TC_DXT1_EXT | BC1_RGBA (macOS-only)| BC1_RGBA_UNORM 199 */ 200 enum class CompressionType { 201 kNone, 202 kETC2_RGB8_UNORM, // the same as ETC1 203 204 kBC1_RGB8_UNORM, 205 kBC1_RGBA8_UNORM, 206 kLast = kBC1_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 /** 685 * makeRawShader functions like makeShader, but for images that contain non-color data. 686 * This includes images encoding things like normals, material properties (eg, roughness), 687 * heightmaps, or any other purely mathematical data that happens to be stored in an image. 688 * These types of images are useful with some programmable shaders (see: SkRuntimeEffect). 689 * 690 * Raw image shaders work like regular image shaders (including filtering and tiling), with 691 * a few major differences: 692 * - No color space transformation is ever applied (the color space of the image is ignored). 693 * - Images with an alpha type of kUnpremul are *not* automatically premultiplied. 694 * - Bicubic filtering is not supported. If SkSamplingOptions::useCubic is true, these 695 * factories will return nullptr. 696 */ 697 sk_sp<SkShader> makeRawShader(SkTileMode tmx, SkTileMode tmy, const SkSamplingOptions&, 698 const SkMatrix* localMatrix = nullptr) const; 699 makeRawShader(SkTileMode tmx,SkTileMode tmy,const SkSamplingOptions & sampling,const SkMatrix & lm)700 sk_sp<SkShader> makeRawShader(SkTileMode tmx, SkTileMode tmy, const SkSamplingOptions& sampling, 701 const SkMatrix& lm) const { 702 return this->makeRawShader(tmx, tmy, sampling, &lm); 703 } makeRawShader(const SkSamplingOptions & sampling,const SkMatrix & lm)704 sk_sp<SkShader> makeRawShader(const SkSamplingOptions& sampling, const SkMatrix& lm) const { 705 return this->makeRawShader(SkTileMode::kClamp, SkTileMode::kClamp, sampling, &lm); 706 } 707 sk_sp<SkShader> makeRawShader(const SkSamplingOptions& sampling, 708 const SkMatrix* lm = nullptr) const { 709 return this->makeRawShader(SkTileMode::kClamp, SkTileMode::kClamp, sampling, lm); 710 } 711 712 using CubicResampler = SkCubicResampler; 713 714 /** Copies SkImage pixel address, row bytes, and SkImageInfo to pixmap, if address 715 is available, and returns true. If pixel address is not available, return 716 false and leave pixmap unchanged. 717 718 @param pixmap storage for pixel state if pixels are readable; otherwise, ignored 719 @return true if SkImage has direct access to pixels 720 721 example: https://fiddle.skia.org/c/@Image_peekPixels 722 */ 723 bool peekPixels(SkPixmap* pixmap) const; 724 725 /** Returns true the contents of SkImage was created on or uploaded to GPU memory, 726 and is available as a GPU texture. 727 728 @return true if SkImage is a GPU texture 729 730 example: https://fiddle.skia.org/c/@Image_isTextureBacked 731 */ 732 bool isTextureBacked() const; 733 734 /** Returns an approximation of the amount of texture memory used by the image. Returns 735 zero if the image is not texture backed or if the texture has an external format. 736 */ 737 size_t textureSize() const; 738 739 /** Returns true if SkImage can be drawn on either raster surface or GPU surface. 740 If context is nullptr, tests if SkImage draws on raster surface; 741 otherwise, tests if SkImage draws on GPU surface associated with context. 742 743 SkImage backed by GPU texture may become invalid if associated context is 744 invalid. lazy image may be invalid and may not draw to raster surface or 745 GPU surface or both. 746 747 @param context GPU context 748 @return true if SkImage can be drawn 749 750 example: https://fiddle.skia.org/c/@Image_isValid 751 */ 752 bool isValid(GrRecordingContext* context) const; 753 754 #if SK_SUPPORT_GPU 755 /** Flushes any pending uses of texture-backed images in the GPU backend. If the image is not 756 texture-backed (including promise texture images) or if the GrDirectContext does not 757 have the same context ID as the context backing the image then this is a no-op. 758 759 If the image was not used in any non-culled draws in the current queue of work for the 760 passed GrDirectContext then this is a no-op unless the GrFlushInfo contains semaphores or 761 a finish proc. Those are respected even when the image has not been used. 762 763 @param context the context on which to flush pending usages of the image. 764 @param info flush options 765 */ 766 GrSemaphoresSubmitted flush(GrDirectContext* context, const GrFlushInfo& flushInfo) const; 767 flush(GrDirectContext * context)768 void flush(GrDirectContext* context) const { this->flush(context, {}); } 769 770 /** Version of flush() that uses a default GrFlushInfo. Also submits the flushed work to the 771 GPU. 772 */ 773 void flushAndSubmit(GrDirectContext*) const; 774 775 /** Retrieves the back-end texture. If SkImage has no back-end texture, an invalid 776 object is returned. Call GrBackendTexture::isValid to determine if the result 777 is valid. 778 779 If flushPendingGrContextIO is true, completes deferred I/O operations. 780 781 If origin in not nullptr, copies location of content drawn into SkImage. 782 783 @param flushPendingGrContextIO flag to flush outstanding requests 784 @return back-end API texture handle; invalid on failure 785 */ 786 GrBackendTexture getBackendTexture(bool flushPendingGrContextIO, 787 GrSurfaceOrigin* origin = nullptr) const; 788 #endif // SK_SUPPORT_GPU 789 790 /** \enum SkImage::CachingHint 791 CachingHint selects whether Skia may internally cache SkBitmap generated by 792 decoding SkImage, or by copying SkImage from GPU to CPU. The default behavior 793 allows caching SkBitmap. 794 795 Choose kDisallow_CachingHint if SkImage pixels are to be used only once, or 796 if SkImage pixels reside in a cache outside of Skia, or to reduce memory pressure. 797 798 Choosing kAllow_CachingHint does not ensure that pixels will be cached. 799 SkImage pixels may not be cached if memory requirements are too large or 800 pixels are not accessible. 801 */ 802 enum CachingHint { 803 kAllow_CachingHint, //!< allows internally caching decoded and copied pixels 804 kDisallow_CachingHint, //!< disallows internally caching decoded and copied pixels 805 }; 806 807 /** Copies SkRect of pixels from SkImage to dstPixels. Copy starts at offset (srcX, srcY), 808 and does not exceed SkImage (width(), height()). 809 810 dstInfo specifies width, height, SkColorType, SkAlphaType, and SkColorSpace of 811 destination. dstRowBytes specifies the gap from one destination row to the next. 812 Returns true if pixels are copied. Returns false if: 813 - dstInfo.addr() equals nullptr 814 - dstRowBytes is less than dstInfo.minRowBytes() 815 - SkPixelRef is nullptr 816 817 Pixels are copied only if pixel conversion is possible. If SkImage SkColorType is 818 kGray_8_SkColorType, or kAlpha_8_SkColorType; dstInfo.colorType() must match. 819 If SkImage SkColorType is kGray_8_SkColorType, dstInfo.colorSpace() must match. 820 If SkImage SkAlphaType is kOpaque_SkAlphaType, dstInfo.alphaType() must 821 match. If SkImage SkColorSpace is nullptr, dstInfo.colorSpace() must match. Returns 822 false if pixel conversion is not possible. 823 824 srcX and srcY may be negative to copy only top or left of source. Returns 825 false if width() or height() is zero or negative. 826 Returns false if abs(srcX) >= Image width(), or if abs(srcY) >= Image height(). 827 828 If cachingHint is kAllow_CachingHint, pixels may be retained locally. 829 If cachingHint is kDisallow_CachingHint, pixels are not added to the local cache. 830 831 @param context the GrDirectContext in play, if it exists 832 @param dstInfo destination width, height, SkColorType, SkAlphaType, SkColorSpace 833 @param dstPixels destination pixel storage 834 @param dstRowBytes destination row length 835 @param srcX column index whose absolute value is less than width() 836 @param srcY row index whose absolute value is less than height() 837 @param cachingHint whether the pixels should be cached locally 838 @return true if pixels are copied to dstPixels 839 */ 840 bool readPixels(GrDirectContext* context, 841 const SkImageInfo& dstInfo, 842 void* dstPixels, 843 size_t dstRowBytes, 844 int srcX, int srcY, 845 CachingHint cachingHint = kAllow_CachingHint) const; 846 847 /** Copies a SkRect of pixels from SkImage to dst. Copy starts at (srcX, srcY), and 848 does not exceed SkImage (width(), height()). 849 850 dst specifies width, height, SkColorType, SkAlphaType, SkColorSpace, pixel storage, 851 and row bytes of destination. dst.rowBytes() specifics the gap from one destination 852 row to the next. Returns true if pixels are copied. Returns false if: 853 - dst pixel storage equals nullptr 854 - dst.rowBytes is less than SkImageInfo::minRowBytes 855 - SkPixelRef is nullptr 856 857 Pixels are copied only if pixel conversion is possible. If SkImage SkColorType is 858 kGray_8_SkColorType, or kAlpha_8_SkColorType; dst.colorType() must match. 859 If SkImage SkColorType is kGray_8_SkColorType, dst.colorSpace() must match. 860 If SkImage SkAlphaType is kOpaque_SkAlphaType, dst.alphaType() must 861 match. If SkImage SkColorSpace is nullptr, dst.colorSpace() must match. Returns 862 false if pixel conversion is not possible. 863 864 srcX and srcY may be negative to copy only top or left of source. Returns 865 false if width() or height() is zero or negative. 866 Returns false if abs(srcX) >= Image width(), or if abs(srcY) >= Image height(). 867 868 If cachingHint is kAllow_CachingHint, pixels may be retained locally. 869 If cachingHint is kDisallow_CachingHint, pixels are not added to the local cache. 870 871 @param context the GrDirectContext in play, if it exists 872 @param dst destination SkPixmap: SkImageInfo, pixels, row bytes 873 @param srcX column index whose absolute value is less than width() 874 @param srcY row index whose absolute value is less than height() 875 @param cachingHint whether the pixels should be cached locallyZ 876 @return true if pixels are copied to dst 877 */ 878 bool readPixels(GrDirectContext* context, 879 const SkPixmap& dst, 880 int srcX, 881 int srcY, 882 CachingHint cachingHint = kAllow_CachingHint) const; 883 884 #ifndef SK_IMAGE_READ_PIXELS_DISABLE_LEGACY_API 885 /** Deprecated. Use the variants that accept a GrDirectContext. */ 886 bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes, 887 int srcX, int srcY, CachingHint cachingHint = kAllow_CachingHint) const; 888 bool readPixels(const SkPixmap& dst, int srcX, int srcY, 889 CachingHint cachingHint = kAllow_CachingHint) const; 890 #endif 891 892 /** The result from asyncRescaleAndReadPixels() or asyncRescaleAndReadPixelsYUV420(). */ 893 class AsyncReadResult { 894 public: 895 AsyncReadResult(const AsyncReadResult&) = delete; 896 AsyncReadResult(AsyncReadResult&&) = delete; 897 AsyncReadResult& operator=(const AsyncReadResult&) = delete; 898 AsyncReadResult& operator=(AsyncReadResult&&) = delete; 899 900 virtual ~AsyncReadResult() = default; 901 virtual int count() const = 0; 902 virtual const void* data(int i) const = 0; 903 virtual size_t rowBytes(int i) const = 0; 904 905 protected: 906 AsyncReadResult() = default; 907 }; 908 909 /** Client-provided context that is passed to client-provided ReadPixelsContext. */ 910 using ReadPixelsContext = void*; 911 912 /** Client-provided callback to asyncRescaleAndReadPixels() or 913 asyncRescaleAndReadPixelsYUV420() that is called when read result is ready or on failure. 914 */ 915 using ReadPixelsCallback = void(ReadPixelsContext, std::unique_ptr<const AsyncReadResult>); 916 917 enum class RescaleGamma : bool { kSrc, kLinear }; 918 919 enum class RescaleMode { 920 kNearest, 921 kRepeatedLinear, 922 kRepeatedCubic, 923 }; 924 925 /** Makes image pixel data available to caller, possibly asynchronously. It can also rescale 926 the image pixels. 927 928 Currently asynchronous reads are only supported on the GPU backend and only when the 929 underlying 3D API supports transfer buffers and CPU/GPU synchronization primitives. In all 930 other cases this operates synchronously. 931 932 Data is read from the source sub-rectangle, is optionally converted to a linear gamma, is 933 rescaled to the size indicated by 'info', is then converted to the color space, color type, 934 and alpha type of 'info'. A 'srcRect' that is not contained by the bounds of the image 935 causes failure. 936 937 When the pixel data is ready the caller's ReadPixelsCallback is called with a 938 AsyncReadResult containing pixel data in the requested color type, alpha type, and color 939 space. The AsyncReadResult will have count() == 1. Upon failure the callback is called with 940 nullptr for AsyncReadResult. For a GPU image this flushes work but a submit must occur to 941 guarantee a finite time before the callback is called. 942 943 The data is valid for the lifetime of AsyncReadResult with the exception that if the SkImage 944 is GPU-backed the data is immediately invalidated if the context is abandoned or 945 destroyed. 946 947 @param info info of the requested pixels 948 @param srcRect subrectangle of image to read 949 @param rescaleGamma controls whether rescaling is done in the image's gamma or whether 950 the source data is transformed to a linear gamma before rescaling. 951 @param rescaleMode controls the technique (and cost) of the rescaling 952 @param callback function to call with result of the read 953 @param context passed to callback 954 */ 955 void asyncRescaleAndReadPixels(const SkImageInfo& info, 956 const SkIRect& srcRect, 957 RescaleGamma rescaleGamma, 958 RescaleMode rescaleMode, 959 ReadPixelsCallback callback, 960 ReadPixelsContext context) const; 961 962 /** 963 Similar to asyncRescaleAndReadPixels but performs an additional conversion to YUV. The 964 RGB->YUV conversion is controlled by 'yuvColorSpace'. The YUV data is returned as three 965 planes ordered y, u, v. The u and v planes are half the width and height of the resized 966 rectangle. The y, u, and v values are single bytes. Currently this fails if 'dstSize' 967 width and height are not even. A 'srcRect' that is not contained by the bounds of the 968 image causes failure. 969 970 When the pixel data is ready the caller's ReadPixelsCallback is called with a 971 AsyncReadResult containing the planar data. The AsyncReadResult will have count() == 3. 972 Upon failure the callback is called with nullptr for AsyncReadResult. For a GPU image this 973 flushes work but a submit must occur to guarantee a finite time before the callback is 974 called. 975 976 The data is valid for the lifetime of AsyncReadResult with the exception that if the SkImage 977 is GPU-backed the data is immediately invalidated if the context is abandoned or 978 destroyed. 979 980 @param yuvColorSpace The transformation from RGB to YUV. Applied to the resized image 981 after it is converted to dstColorSpace. 982 @param dstColorSpace The color space to convert the resized image to, after rescaling. 983 @param srcRect The portion of the image to rescale and convert to YUV planes. 984 @param dstSize The size to rescale srcRect to 985 @param rescaleGamma controls whether rescaling is done in the image's gamma or whether 986 the source data is transformed to a linear gamma before rescaling. 987 @param rescaleMode controls the technique (and cost) of the rescaling 988 @param callback function to call with the planar read result 989 @param context passed to callback 990 */ 991 void asyncRescaleAndReadPixelsYUV420(SkYUVColorSpace yuvColorSpace, 992 sk_sp<SkColorSpace> dstColorSpace, 993 const SkIRect& srcRect, 994 const SkISize& dstSize, 995 RescaleGamma rescaleGamma, 996 RescaleMode rescaleMode, 997 ReadPixelsCallback callback, 998 ReadPixelsContext context) const; 999 1000 /** Copies SkImage to dst, scaling pixels to fit dst.width() and dst.height(), and 1001 converting pixels to match dst.colorType() and dst.alphaType(). Returns true if 1002 pixels are copied. Returns false if dst.addr() is nullptr, or dst.rowBytes() is 1003 less than dst SkImageInfo::minRowBytes. 1004 1005 Pixels are copied only if pixel conversion is possible. If SkImage SkColorType is 1006 kGray_8_SkColorType, or kAlpha_8_SkColorType; dst.colorType() must match. 1007 If SkImage SkColorType is kGray_8_SkColorType, dst.colorSpace() must match. 1008 If SkImage SkAlphaType is kOpaque_SkAlphaType, dst.alphaType() must 1009 match. If SkImage SkColorSpace is nullptr, dst.colorSpace() must match. Returns 1010 false if pixel conversion is not possible. 1011 1012 If cachingHint is kAllow_CachingHint, pixels may be retained locally. 1013 If cachingHint is kDisallow_CachingHint, pixels are not added to the local cache. 1014 1015 @param dst destination SkPixmap: SkImageInfo, pixels, row bytes 1016 @return true if pixels are scaled to fit dst 1017 */ 1018 bool scalePixels(const SkPixmap& dst, const SkSamplingOptions&, 1019 CachingHint cachingHint = kAllow_CachingHint) const; 1020 1021 /** Encodes SkImage pixels, returning result as SkData. 1022 1023 Returns nullptr if encoding fails, or if encodedImageFormat is not supported. 1024 1025 SkImage encoding in a format requires both building with one or more of: 1026 SK_ENCODE_JPEG, SK_ENCODE_PNG, SK_ENCODE_WEBP; and platform support 1027 for the encoded format. 1028 1029 If SK_BUILD_FOR_MAC or SK_BUILD_FOR_IOS is defined, encodedImageFormat can 1030 additionally be one of: SkEncodedImageFormat::kICO, SkEncodedImageFormat::kBMP, 1031 SkEncodedImageFormat::kGIF. 1032 1033 quality is a platform and format specific metric trading off size and encoding 1034 error. When used, quality equaling 100 encodes with the least error. quality may 1035 be ignored by the encoder. 1036 1037 @param encodedImageFormat one of: SkEncodedImageFormat::kJPEG, SkEncodedImageFormat::kPNG, 1038 SkEncodedImageFormat::kWEBP 1039 @param quality encoder specific metric with 100 equaling best 1040 @return encoded SkImage, or nullptr 1041 1042 example: https://fiddle.skia.org/c/@Image_encodeToData 1043 */ 1044 sk_sp<SkData> encodeToData(SkEncodedImageFormat encodedImageFormat, int quality) const; 1045 1046 /** Encodes SkImage pixels, returning result as SkData. Returns existing encoded data 1047 if present; otherwise, SkImage is encoded with SkEncodedImageFormat::kPNG. Skia 1048 must be built with SK_ENCODE_PNG to encode SkImage. 1049 1050 Returns nullptr if existing encoded data is missing or invalid, and 1051 encoding fails. 1052 1053 @return encoded SkImage, or nullptr 1054 1055 example: https://fiddle.skia.org/c/@Image_encodeToData_2 1056 */ 1057 sk_sp<SkData> encodeToData() const; 1058 1059 /** Returns encoded SkImage pixels as SkData, if SkImage was created from supported 1060 encoded stream format. Platform support for formats vary and may require building 1061 with one or more of: SK_ENCODE_JPEG, SK_ENCODE_PNG, SK_ENCODE_WEBP. 1062 1063 Returns nullptr if SkImage contents are not encoded. 1064 1065 @return encoded SkImage, or nullptr 1066 1067 example: https://fiddle.skia.org/c/@Image_refEncodedData 1068 */ 1069 sk_sp<SkData> refEncodedData() const; 1070 1071 /** Returns subset of this image. 1072 1073 Returns nullptr if any of the following are true: 1074 - Subset is empty 1075 - Subset is not contained inside the image's bounds 1076 - Pixels in the image could not be read or copied 1077 1078 If this image is texture-backed, the context parameter is required and must match the 1079 context of the source image. If the context parameter is provided, and the image is 1080 raster-backed, the subset will be converted to texture-backed. 1081 1082 @param subset bounds of returned SkImage 1083 @param context the GrDirectContext in play, if it exists 1084 @return the subsetted image, or nullptr 1085 1086 example: https://fiddle.skia.org/c/@Image_makeSubset 1087 */ 1088 sk_sp<SkImage> makeSubset(const SkIRect& subset, GrDirectContext* direct = nullptr) const; 1089 1090 /** 1091 * Returns true if the image has mipmap levels. 1092 */ 1093 bool hasMipmaps() const; 1094 1095 /** 1096 * Returns an image with the same "base" pixels as the this image, but with mipmap levels 1097 * automatically generated and attached. 1098 */ 1099 sk_sp<SkImage> withDefaultMipmaps() const; 1100 1101 #if SK_SUPPORT_GPU 1102 /** Returns SkImage backed by GPU texture associated with context. Returned SkImage is 1103 compatible with SkSurface created with dstColorSpace. The returned SkImage respects 1104 mipMapped setting; if mipMapped equals GrMipmapped::kYes, the backing texture 1105 allocates mip map levels. 1106 1107 The mipMapped parameter is effectively treated as kNo if MIP maps are not supported by the 1108 GPU. 1109 1110 Returns original SkImage if the image is already texture-backed, the context matches, and 1111 mipMapped is compatible with the backing GPU texture. SkBudgeted is ignored in this case. 1112 1113 Returns nullptr if context is nullptr, or if SkImage was created with another 1114 GrDirectContext. 1115 1116 @param GrDirectContext the GrDirectContext in play, if it exists 1117 @param GrMipmapped whether created SkImage texture must allocate mip map levels 1118 @param SkBudgeted whether to count a newly created texture for the returned image 1119 counts against the context's budget. 1120 @return created SkImage, or nullptr 1121 */ 1122 sk_sp<SkImage> makeTextureImage(GrDirectContext*, 1123 GrMipmapped = GrMipmapped::kNo, 1124 SkBudgeted = SkBudgeted::kYes) const; 1125 #endif 1126 1127 /** Returns raster image or lazy image. Copies SkImage backed by GPU texture into 1128 CPU memory if needed. Returns original SkImage if decoded in raster bitmap, 1129 or if encoded in a stream. 1130 1131 Returns nullptr if backed by GPU texture and copy fails. 1132 1133 @return raster image, lazy image, or nullptr 1134 1135 example: https://fiddle.skia.org/c/@Image_makeNonTextureImage 1136 */ 1137 sk_sp<SkImage> makeNonTextureImage() const; 1138 1139 /** Returns raster image. Copies SkImage backed by GPU texture into CPU memory, 1140 or decodes SkImage from lazy image. Returns original SkImage if decoded in 1141 raster bitmap. 1142 1143 Returns nullptr if copy, decode, or pixel read fails. 1144 1145 If cachingHint is kAllow_CachingHint, pixels may be retained locally. 1146 If cachingHint is kDisallow_CachingHint, pixels are not added to the local cache. 1147 1148 @return raster image, or nullptr 1149 1150 example: https://fiddle.skia.org/c/@Image_makeRasterImage 1151 */ 1152 sk_sp<SkImage> makeRasterImage(CachingHint cachingHint = kDisallow_CachingHint) const; 1153 1154 /** Creates filtered SkImage. filter processes original SkImage, potentially changing 1155 color, position, and size. subset is the bounds of original SkImage processed 1156 by filter. clipBounds is the expected bounds of the filtered SkImage. outSubset 1157 is required storage for the actual bounds of the filtered SkImage. offset is 1158 required storage for translation of returned SkImage. 1159 1160 Returns nullptr if SkImage could not be created or if the recording context provided doesn't 1161 match the GPU context in which the image was created. If nullptr is returned, outSubset 1162 and offset are undefined. 1163 1164 Useful for animation of SkImageFilter that varies size from frame to frame. 1165 Returned SkImage is created larger than required by filter so that GPU texture 1166 can be reused with different sized effects. outSubset describes the valid bounds 1167 of GPU texture returned. offset translates the returned SkImage to keep subsequent 1168 animation frames aligned with respect to each other. 1169 1170 @param context the GrRecordingContext in play - if it exists 1171 @param filter how SkImage is sampled when transformed 1172 @param subset bounds of SkImage processed by filter 1173 @param clipBounds expected bounds of filtered SkImage 1174 @param outSubset storage for returned SkImage bounds 1175 @param offset storage for returned SkImage translation 1176 @return filtered SkImage, or nullptr 1177 */ 1178 sk_sp<SkImage> makeWithFilter(GrRecordingContext* context, 1179 const SkImageFilter* filter, const SkIRect& subset, 1180 const SkIRect& clipBounds, SkIRect* outSubset, 1181 SkIPoint* offset) const; 1182 1183 /** Defines a callback function, taking one parameter of type GrBackendTexture with 1184 no return value. Function is called when back-end texture is to be released. 1185 */ 1186 typedef std::function<void(GrBackendTexture)> BackendTextureReleaseProc; 1187 1188 #if SK_SUPPORT_GPU 1189 /** Creates a GrBackendTexture from the provided SkImage. Returns true and 1190 stores result in backendTexture and backendTextureReleaseProc if 1191 texture is created; otherwise, returns false and leaves 1192 backendTexture and backendTextureReleaseProc unmodified. 1193 1194 Call backendTextureReleaseProc after deleting backendTexture. 1195 backendTextureReleaseProc cleans up auxiliary data related to returned 1196 backendTexture. The caller must delete returned backendTexture after use. 1197 1198 If SkImage is both texture backed and singly referenced, image is returned in 1199 backendTexture without conversion or making a copy. SkImage is singly referenced 1200 if its was transferred solely using std::move(). 1201 1202 If SkImage is not texture backed, returns texture with SkImage contents. 1203 1204 @param context GPU context 1205 @param image SkImage used for texture 1206 @param backendTexture storage for back-end texture 1207 @param backendTextureReleaseProc storage for clean up function 1208 @return true if back-end texture was created 1209 */ 1210 static bool MakeBackendTextureFromSkImage(GrDirectContext* context, 1211 sk_sp<SkImage> image, 1212 GrBackendTexture* backendTexture, 1213 BackendTextureReleaseProc* backendTextureReleaseProc); 1214 #endif 1215 /** Deprecated. 1216 */ 1217 enum LegacyBitmapMode { 1218 kRO_LegacyBitmapMode, //!< returned bitmap is read-only and immutable 1219 }; 1220 1221 /** Deprecated. 1222 Creates raster SkBitmap with same pixels as SkImage. If legacyBitmapMode is 1223 kRO_LegacyBitmapMode, returned bitmap is read-only and immutable. 1224 Returns true if SkBitmap is stored in bitmap. Returns false and resets bitmap if 1225 SkBitmap write did not succeed. 1226 1227 @param bitmap storage for legacy SkBitmap 1228 @param legacyBitmapMode bitmap is read-only and immutable 1229 @return true if SkBitmap was created 1230 */ 1231 bool asLegacyBitmap(SkBitmap* bitmap, 1232 LegacyBitmapMode legacyBitmapMode = kRO_LegacyBitmapMode) const; 1233 1234 /** Returns true if SkImage is backed by an image-generator or other service that creates 1235 and caches its pixels or texture on-demand. 1236 1237 @return true if SkImage is created as needed 1238 1239 example: https://fiddle.skia.org/c/@Image_isLazyGenerated_a 1240 example: https://fiddle.skia.org/c/@Image_isLazyGenerated_b 1241 */ 1242 bool isLazyGenerated() const; 1243 1244 /** Creates SkImage in target SkColorSpace. 1245 Returns nullptr if SkImage could not be created. 1246 1247 Returns original SkImage if it is in target SkColorSpace. 1248 Otherwise, converts pixels from SkImage SkColorSpace to target SkColorSpace. 1249 If SkImage colorSpace() returns nullptr, SkImage SkColorSpace is assumed to be sRGB. 1250 1251 If this image is texture-backed, the context parameter is required and must match the 1252 context of the source image. 1253 1254 @param target SkColorSpace describing color range of returned SkImage 1255 @param direct The GrDirectContext in play, if it exists 1256 @return created SkImage in target SkColorSpace 1257 1258 example: https://fiddle.skia.org/c/@Image_makeColorSpace 1259 */ 1260 sk_sp<SkImage> makeColorSpace(sk_sp<SkColorSpace> target, 1261 GrDirectContext* direct = nullptr) const; 1262 1263 /** Experimental. 1264 Creates SkImage in target SkColorType and SkColorSpace. 1265 Returns nullptr if SkImage could not be created. 1266 1267 Returns original SkImage if it is in target SkColorType and SkColorSpace. 1268 1269 If this image is texture-backed, the context parameter is required and must match the 1270 context of the source image. 1271 1272 @param targetColorType SkColorType of returned SkImage 1273 @param targetColorSpace SkColorSpace of returned SkImage 1274 @param direct The GrDirectContext in play, if it exists 1275 @return created SkImage in target SkColorType and SkColorSpace 1276 */ 1277 sk_sp<SkImage> makeColorTypeAndColorSpace(SkColorType targetColorType, 1278 sk_sp<SkColorSpace> targetColorSpace, 1279 GrDirectContext* direct = nullptr) const; 1280 1281 /** Creates a new SkImage identical to this one, but with a different SkColorSpace. 1282 This does not convert the underlying pixel data, so the resulting image will draw 1283 differently. 1284 */ 1285 sk_sp<SkImage> reinterpretColorSpace(sk_sp<SkColorSpace> newColorSpace) const; 1286 1287 private: 1288 SkImage(const SkImageInfo& info, uint32_t uniqueID); 1289 1290 friend class SkBitmap; 1291 friend class SkImage_Base; 1292 friend class SkMipmapBuilder; 1293 1294 SkImageInfo fInfo; 1295 const uint32_t fUniqueID; 1296 1297 sk_sp<SkImage> withMipmaps(sk_sp<SkMipmap>) const; 1298 1299 using INHERITED = SkRefCnt; 1300 }; 1301 1302 #endif 1303