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#include "SkImageDecoder.h"
9#include "SkImage_Base.h"
10#include "SkBitmap.h"
11#include "SkCanvas.h"
12#include "SkData.h"
13
14class SkImage_Codec : public SkImage_Base {
15public:
16    static SkImage* NewEmpty();
17
18    SkImage_Codec(SkData* encodedData, int width, int height);
19    virtual ~SkImage_Codec();
20
21    virtual void onDraw(SkCanvas*, SkScalar, SkScalar, const SkPaint*) SK_OVERRIDE;
22    virtual void onDrawRectToRect(SkCanvas*, const SkRect*, const SkRect&, const SkPaint*) SK_OVERRIDE;
23
24private:
25    SkData*     fEncodedData;
26    SkBitmap    fBitmap;
27
28    typedef SkImage_Base INHERITED;
29};
30
31///////////////////////////////////////////////////////////////////////////////
32
33SkImage_Codec::SkImage_Codec(SkData* data, int width, int height) : INHERITED(width, height) {
34    fEncodedData = data;
35    fEncodedData->ref();
36}
37
38SkImage_Codec::~SkImage_Codec() {
39    fEncodedData->unref();
40}
41
42void SkImage_Codec::onDraw(SkCanvas* canvas, SkScalar x, SkScalar y, const SkPaint* paint) {
43    if (!fBitmap.pixelRef()) {
44        if (!SkImageDecoder::DecodeMemory(fEncodedData->bytes(), fEncodedData->size(),
45                                          &fBitmap)) {
46            return;
47        }
48    }
49    canvas->drawBitmap(fBitmap, x, y, paint);
50}
51
52void SkImage_Codec::onDrawRectToRect(SkCanvas* canvas, const SkRect* src,
53                                     const SkRect& dst, const SkPaint* paint) {
54    if (!fBitmap.pixelRef()) {
55        if (!SkImageDecoder::DecodeMemory(fEncodedData->bytes(), fEncodedData->size(),
56                                          &fBitmap)) {
57            return;
58        }
59    }
60    canvas->drawBitmapRectToRect(fBitmap, src, dst, paint);
61}
62
63///////////////////////////////////////////////////////////////////////////////
64
65SkImage* SkImage::NewEncodedData(SkData* data) {
66    if (NULL == data) {
67        return NULL;
68    }
69
70    SkBitmap bitmap;
71    if (!SkImageDecoder::DecodeMemory(data->bytes(), data->size(), &bitmap,
72                                      SkBitmap::kNo_Config,
73                                      SkImageDecoder::kDecodeBounds_Mode)) {
74        return NULL;
75    }
76
77    return SkNEW_ARGS(SkImage_Codec, (data, bitmap.width(), bitmap.height()));
78}
79