Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / image / SkImage_Codec.cpp
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
14 class SkImage_Codec : public SkImage_Base {
15 public:
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*) const SK_OVERRIDE;
22     virtual void onDrawRectToRect(SkCanvas*, const SkRect*, const SkRect&,
23                                   const SkPaint*) const SK_OVERRIDE;
24
25 private:
26     SkData*     fEncodedData;
27     SkBitmap    fBitmap;
28
29     typedef SkImage_Base INHERITED;
30 };
31
32 ///////////////////////////////////////////////////////////////////////////////
33
34 SkImage_Codec::SkImage_Codec(SkData* data, int width, int height) : INHERITED(width, height) {
35     fEncodedData = data;
36     fEncodedData->ref();
37 }
38
39 SkImage_Codec::~SkImage_Codec() {
40     fEncodedData->unref();
41 }
42
43 void SkImage_Codec::onDraw(SkCanvas* canvas, SkScalar x, SkScalar y, const SkPaint* paint) const {
44     if (!fBitmap.pixelRef()) {
45         // todo: this needs to be thread-safe
46         SkBitmap* bitmap = const_cast<SkBitmap*>(&fBitmap);
47         if (!SkImageDecoder::DecodeMemory(fEncodedData->bytes(), fEncodedData->size(), bitmap)) {
48             return;
49         }
50     }
51     canvas->drawBitmap(fBitmap, x, y, paint);
52 }
53
54 void SkImage_Codec::onDrawRectToRect(SkCanvas* canvas, const SkRect* src, const SkRect& dst,
55                                      const SkPaint* paint) const {
56     if (!fBitmap.pixelRef()) {
57         // todo: this needs to be thread-safe
58         SkBitmap* bitmap = const_cast<SkBitmap*>(&fBitmap);
59         if (!SkImageDecoder::DecodeMemory(fEncodedData->bytes(), fEncodedData->size(), bitmap)) {
60             return;
61         }
62     }
63     canvas->drawBitmapRectToRect(fBitmap, src, dst, paint);
64 }
65
66 ///////////////////////////////////////////////////////////////////////////////
67
68 SkImage* SkImage::NewEncodedData(SkData* data) {
69     if (NULL == data) {
70         return NULL;
71     }
72
73     SkBitmap bitmap;
74     if (!SkImageDecoder::DecodeMemory(data->bytes(), data->size(), &bitmap, kUnknown_SkColorType,
75                                       SkImageDecoder::kDecodeBounds_Mode)) {
76         return NULL;
77     }
78
79     return SkNEW_ARGS(SkImage_Codec, (data, bitmap.width(), bitmap.height()));
80 }