1 /*
2 * Copyright 2016 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 DecodeFile_DEFINED
9 #define DecodeFile_DEFINED
10
11 #include "include/codec/SkCodec.h"
12 #include "include/core/SkBitmap.h"
13 #include "include/core/SkData.h"
14 #include "include/core/SkImage.h"
15
16 static inline bool decode_file(sk_sp<SkData> data, SkBitmap* bitmap,
17 SkColorType colorType = kN32_SkColorType,
18 bool requireUnpremul = false) {
19 std::unique_ptr<SkCodec> codec = SkCodec::MakeFromData(std::move(data));
20 if (!codec) {
21 return false;
22 }
23
24 SkImageInfo info = codec->getInfo().makeColorType(colorType);
25 if (requireUnpremul && kPremul_SkAlphaType == info.alphaType()) {
26 info = info.makeAlphaType(kUnpremul_SkAlphaType);
27 }
28
29 if (!bitmap->tryAllocPixels(info)) {
30 return false;
31 }
32
33 return SkCodec::kSuccess == codec->getPixels(info, bitmap->getPixels(), bitmap->rowBytes());
34 }
35
36 static inline bool decode_file(const char* filename, SkBitmap* bitmap,
37 SkColorType colorType = kN32_SkColorType,
38 bool requireUnpremul = false) {
39 return decode_file(SkData::MakeFromFileName(filename), bitmap, colorType, requireUnpremul);
40 }
41
decode_file(const char filename[])42 static inline sk_sp<SkImage> decode_file(const char filename[]) {
43 sk_sp<SkData> data(SkData::MakeFromFileName(filename));
44 return data ? SkImage::MakeFromEncoded(data) : nullptr;
45 }
46 #endif // DecodeFile_DEFINED
47