SkImage.h revision d82bc7b90ab0a88d6fb401994f3763d3057ab6e7
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 "SkFilterQuality.h"
12#include "SkImageInfo.h"
13#include "SkImageEncoder.h"
14#include "SkRefCnt.h"
15#include "SkScalar.h"
16#include "SkShader.h"
17
18class SkData;
19class SkCanvas;
20class SkColorTable;
21class SkImageGenerator;
22class SkPaint;
23class SkPicture;
24class SkPixelSerializer;
25class SkString;
26class SkSurface;
27class GrContext;
28class GrTexture;
29
30/**
31 *  SkImage is an abstraction for drawing a rectagle of pixels, though the
32 *  particular type of image could be actually storing its data on the GPU, or
33 *  as drawing commands (picture or PDF or otherwise), ready to be played back
34 *  into another canvas.
35 *
36 *  The content of SkImage is always immutable, though the actual storage may
37 *  change, if for example that image can be re-created via encoded data or
38 *  other means.
39 *
40 *  SkImage always has a non-zero dimensions. If there is a request to create a new image, either
41 *  directly or via SkSurface, and either of the requested dimensions are zero, then NULL will be
42 *  returned.
43 */
44class SK_API SkImage : public SkRefCnt {
45public:
46    typedef SkImageInfo Info;
47    typedef void* ReleaseContext;
48
49    static SkImage* NewRasterCopy(const Info&, const void* pixels, size_t rowBytes,
50                                  SkColorTable* ctable = NULL);
51    static SkImage* NewRasterData(const Info&, SkData* pixels, size_t rowBytes);
52
53    typedef void (*RasterReleaseProc)(const void* pixels, ReleaseContext);
54
55    /**
56     *  Return a new Image referencing the specified pixels. These must remain valid and unchanged
57     *  until the specified release-proc is called, indicating that Skia no longer has a reference
58     *  to the pixels.
59     *
60     *  Returns NULL if the requested Info is unsupported.
61     */
62    static SkImage* NewFromRaster(const Info&, const void* pixels, size_t rowBytes,
63                                  RasterReleaseProc, ReleaseContext);
64
65    /**
66     *  Construct a new image from the specified bitmap. If the bitmap is marked immutable, and
67     *  its pixel memory is shareable, it may be shared instead of copied.
68     */
69    static SkImage* NewFromBitmap(const SkBitmap&);
70
71    /**
72     *  Construct a new SkImage based on the given ImageGenerator.
73     *  This function will always take ownership of the passed
74     *  ImageGenerator.  Returns NULL on error.
75     *
76     *  If a subset is specified, it must be contained within the generator's bounds.
77     */
78    static SkImage* NewFromGenerator(SkImageGenerator*, const SkIRect* subset = NULL);
79
80    /**
81     *  Construct a new SkImage based on the specified encoded data. Returns NULL on failure,
82     *  which can mean that the format of the encoded data was not recognized/supported.
83     *
84     *  If a subset is specified, it must be contained within the encoded data's bounds.
85     *
86     *  Regardless of success or failure, the caller is responsible for managing their ownership
87     *  of the data.
88     */
89    static SkImage* NewFromEncoded(SkData* encoded, const SkIRect* subset = NULL);
90
91    /**
92     *  Create a new image from the specified descriptor. Note - the caller is responsible for
93     *  managing the lifetime of the underlying platform texture.
94     *
95     *  Will return NULL if the specified descriptor is unsupported.
96     */
97    static SkImage* NewFromTexture(GrContext* ctx, const GrBackendTextureDesc& desc) {
98        return NewFromTexture(ctx, desc, kPremul_SkAlphaType, NULL, NULL);
99    }
100
101    static SkImage* NewFromTexture(GrContext* ctx, const GrBackendTextureDesc& de, SkAlphaType at) {
102        return NewFromTexture(ctx, de, at, NULL, NULL);
103    }
104
105    typedef void (*TextureReleaseProc)(ReleaseContext);
106
107    /**
108     *  Create a new image from the specified descriptor. The underlying platform texture must stay
109     *  valid and unaltered until the specified release-proc is invoked, indicating that Skia
110     *  no longer is holding a reference to it.
111     *
112     *  Will return NULL if the specified descriptor is unsupported.
113     */
114    static SkImage* NewFromTexture(GrContext*, const GrBackendTextureDesc&, SkAlphaType,
115                                   TextureReleaseProc, ReleaseContext);
116
117    /**
118     *  Create a new image from the specified descriptor. Note - Skia will delete or recycle the
119     *  texture when the image is released.
120     *
121     *  Will return NULL if the specified descriptor is unsupported.
122     */
123    static SkImage* NewFromAdoptedTexture(GrContext*, const GrBackendTextureDesc&,
124                                          SkAlphaType = kPremul_SkAlphaType);
125
126    /**
127     *  Create a new image by copying the pixels from the specified descriptor. No reference is
128     *  kept to the original platform texture.
129     *
130     *  Will return NULL if the specified descriptor is unsupported.
131     */
132    static SkImage* NewFromTextureCopy(GrContext*, const GrBackendTextureDesc&,
133                                       SkAlphaType = kPremul_SkAlphaType);
134
135    /**
136     *  Create a new image by copying the pixels from the specified y, u, v textures. The data
137     *  from the textures is immediately ingested into the image and the textures can be modified or
138     *  deleted after the function returns. The image will have the dimensions of the y texture.
139     */
140    static SkImage* NewFromYUVTexturesCopy(GrContext*, SkYUVColorSpace,
141                                           const GrBackendObject yuvTextureHandles[3],
142                                           const SkISize yuvSizes[3],
143                                           GrSurfaceOrigin);
144
145    static SkImage* NewFromPicture(const SkPicture*, const SkISize& dimensions,
146                                   const SkMatrix*, const SkPaint*);
147
148    ///////////////////////////////////////////////////////////////////////////////////////////////
149
150    int width() const { return fWidth; }
151    int height() const { return fHeight; }
152    SkISize dimensions() const { return SkISize::Make(fWidth, fHeight); }
153    SkIRect bounds() const { return SkIRect::MakeWH(fWidth, fHeight); }
154    uint32_t uniqueID() const { return fUniqueID; }
155    virtual bool isOpaque() const { return false; }
156
157    virtual SkShader* newShader(SkShader::TileMode,
158                                SkShader::TileMode,
159                                const SkMatrix* localMatrix = NULL) const;
160
161    /**
162     *  If the image has direct access to its pixels (i.e. they are in local
163     *  RAM) return the (const) address of those pixels, and if not null, return
164     *  the ImageInfo and rowBytes. The returned address is only valid while
165     *  the image object is in scope.
166     *
167     *  On failure, returns NULL and the info and rowBytes parameters are
168     *  ignored.
169     */
170    const void* peekPixels(SkImageInfo* info, size_t* rowBytes) const;
171
172    /**
173     *  If the image has direct access to its pixels (i.e. they are in local
174     *  RAM) return the (const) address of those pixels, and if not null, return
175     *  true, and if pixmap is not NULL, set it to point into the image.
176     *
177     *  On failure, return false and ignore the pixmap parameter.
178     */
179    bool peekPixels(SkPixmap* pixmap) const;
180
181    /**
182     *  Some images have to perform preliminary work in preparation for drawing. This can be
183     *  decoding, uploading to a GPU, or other tasks. These happen automatically when an image
184     *  is drawn, and often they are cached so that the cost is only paid the first time.
185     *
186     *  Preroll() can be called before drawing to try to perform this prepatory work ahead of time.
187     *  For images that have no such work, this returns instantly. Others may do some thing to
188     *  prepare their cache and then return.
189     *
190     *  If the image will drawn to a GPU-backed canvas or surface, pass the associated GrContext.
191     *  If the image will be drawn to any other type of canvas or surface, pass null.
192     */
193    void preroll(GrContext* = nullptr) const;
194
195    // DEPRECATED
196    GrTexture* getTexture() const;
197
198    /**
199     *  Returns true if the image is texture backed.
200     */
201    bool isTextureBacked() const;
202
203    /**
204     *  Retrieves the backend API handle of the texture. If flushPendingGrContextIO then the
205     *  GrContext will issue to the backend API any deferred IO operations on the texture before
206     *  returning.
207     */
208    GrBackendObject getTextureHandle(bool flushPendingGrContextIO) const;
209
210    /**
211     *  Copy the pixels from the image into the specified buffer (pixels + rowBytes),
212     *  converting them into the requested format (dstInfo). The image pixels are read
213     *  starting at the specified (srcX,srcY) location.
214     *
215     *  The specified ImageInfo and (srcX,srcY) offset specifies a source rectangle
216     *
217     *      srcR.setXYWH(srcX, srcY, dstInfo.width(), dstInfo.height());
218     *
219     *  srcR is intersected with the bounds of the image. If this intersection is not empty,
220     *  then we have two sets of pixels (of equal size). Replace the dst pixels with the
221     *  corresponding src pixels, performing any colortype/alphatype transformations needed
222     *  (in the case where the src and dst have different colortypes or alphatypes).
223     *
224     *  This call can fail, returning false, for several reasons:
225     *  - If srcR does not intersect the image bounds.
226     *  - If the requested colortype/alphatype cannot be converted from the image's types.
227     */
228    bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
229                    int srcX, int srcY) const;
230
231    bool readPixels(const SkPixmap& dst, int srcX, int srcY) const;
232
233    /**
234     *  Encode the image's pixels and return the result as a new SkData, which
235     *  the caller must manage (i.e. call unref() when they are done).
236     *
237     *  If the image type cannot be encoded, or the requested encoder type is
238     *  not supported, this will return NULL.
239     *
240     *  Note: this will attempt to encode the image's pixels in the specified format,
241     *  even if the image returns a data from refEncoded(). That data will be ignored.
242     */
243    SkData* encode(SkImageEncoder::Type, int quality) const;
244
245    /**
246     *  Encode the image and return the result as a caller-managed SkData.  This will
247     *  attempt to reuse existing encoded data (as returned by refEncoded).
248     *
249     *  We defer to the SkPixelSerializer both for vetting existing encoded data
250     *  (useEncodedData) and for encoding the image (encodePixels) when no such data is
251     *  present or is rejected by the serializer.
252     *
253     *  If not specified, we use a default serializer which 1) always accepts existing data
254     *  (in any format) and 2) encodes to PNG.
255     *
256     *  If no compatible encoded data exists and encoding fails, this method will also
257     *  fail (return NULL).
258     */
259    SkData* encode(SkPixelSerializer* = nullptr) const;
260
261    /**
262     *  If the image already has its contents in encoded form (e.g. PNG or JPEG), return a ref
263     *  to that data (which the caller must call unref() on). The caller is responsible for calling
264     *  unref on the data when they are done.
265     *
266     *  If the image does not already has its contents in encoded form, return NULL.
267     *
268     *  Note: to force the image to return its contents as encoded data, try calling encode(...).
269     */
270    SkData* refEncoded() const;
271
272    const char* toString(SkString*) const;
273
274    /**
275     *  Return a new image that is a subset of this image. The underlying implementation may
276     *  share the pixels, or it may make a copy.
277     *
278     *  If subset does not intersect the bounds of this image, or the copy/share cannot be made,
279     *  NULL will be returned.
280     */
281    SkImage* newSubset(const SkIRect& subset) const;
282
283    // Helper functions to convert to SkBitmap
284
285    enum LegacyBitmapMode {
286        kRO_LegacyBitmapMode,
287        kRW_LegacyBitmapMode,
288    };
289
290    /**
291     *  Attempt to create a bitmap with the same pixels as the image. The result will always be
292     *  a raster-backed bitmap (texture-backed bitmaps are DEPRECATED, and not supported here).
293     *
294     *  If the mode is kRO (read-only), the resulting bitmap will be marked as immutable.
295     *
296     *  On succcess, returns true. On failure, returns false and the bitmap parameter will be reset
297     *  to empty.
298     */
299    bool asLegacyBitmap(SkBitmap*, LegacyBitmapMode) const;
300
301    /**
302     *  Returns true if the image is backed by an image-generator or other src that creates
303     *  (and caches) its pixels / texture on-demand.
304     */
305    bool isLazyGenerated() const;
306
307    /**
308     *  Apply the specified filter to this image, and return the result as a new image.
309     *
310     *  if forceResultToOriginalSize is true, then the resulting image will be the same size as the
311     *  src, regardless of the normal output of the filter.
312     *
313     *  If offset is non-null, it is set to the relative offset needed to draw the resulting image
314     *  in the same logical place as the original.
315     *
316     *  e.g.
317     *      If the filter makes the result larger by a margin of 4 the output would be:
318     *          result->width()  == this->width + 8
319     *          result->height() == this->height + 8
320     *          offset.x()       == -4
321     *          offset.y()       == -4
322     *
323     *  If the filter fails to create a resulting image, null is returned, and the offset parameter
324     *  (if specified) will be undefined.
325     */
326    SkImage* applyFilter(SkImageFilter* filter, SkIPoint* offset,
327                         bool forceResultToOriginalSize) const;
328
329protected:
330    SkImage(int width, int height, uint32_t uniqueID);
331
332private:
333    const int       fWidth;
334    const int       fHeight;
335    const uint32_t  fUniqueID;
336
337    typedef SkRefCnt INHERITED;
338};
339
340#endif
341