msarett | d15750c | 2016-03-18 15:48:49 -0700 | [diff] [blame] | 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 | |
Hal Canary | 03a7f5f | 2017-02-10 09:06:38 -0500 | [diff] [blame] | 8 | #ifndef DecodeFile_DEFINED |
| 9 | #define DecodeFile_DEFINED |
| 10 | |
msarett | d15750c | 2016-03-18 15:48:49 -0700 | [diff] [blame] | 11 | #include "SkBitmap.h" |
| 12 | #include "SkCodec.h" |
| 13 | #include "SkData.h" |
reed | ccebcec | 2016-08-22 07:41:46 -0700 | [diff] [blame] | 14 | #include "SkImage.h" |
msarett | d15750c | 2016-03-18 15:48:49 -0700 | [diff] [blame] | 15 | |
reed | ccebcec | 2016-08-22 07:41:46 -0700 | [diff] [blame] | 16 | static inline bool decode_file(const char* filename, SkBitmap* bitmap, |
| 17 | SkColorType colorType = kN32_SkColorType, |
| 18 | bool requireUnpremul = false) { |
msarett | d15750c | 2016-03-18 15:48:49 -0700 | [diff] [blame] | 19 | SkASSERT(kIndex_8_SkColorType != colorType); |
bungeman | 38d909e | 2016-08-02 14:40:46 -0700 | [diff] [blame] | 20 | sk_sp<SkData> data(SkData::MakeFromFileName(filename)); |
Ben Wagner | 145dbcd | 2016-11-03 14:40:50 -0400 | [diff] [blame] | 21 | std::unique_ptr<SkCodec> codec(SkCodec::NewFromData(data)); |
msarett | d15750c | 2016-03-18 15:48:49 -0700 | [diff] [blame] | 22 | if (!codec) { |
| 23 | return false; |
| 24 | } |
| 25 | |
| 26 | SkImageInfo info = codec->getInfo().makeColorType(colorType); |
| 27 | if (requireUnpremul && kPremul_SkAlphaType == info.alphaType()) { |
| 28 | info = info.makeAlphaType(kUnpremul_SkAlphaType); |
| 29 | } |
| 30 | |
| 31 | if (!bitmap->tryAllocPixels(info)) { |
| 32 | return false; |
| 33 | } |
| 34 | |
| 35 | return SkCodec::kSuccess == codec->getPixels(info, bitmap->getPixels(), bitmap->rowBytes()); |
| 36 | } |
reed | ccebcec | 2016-08-22 07:41:46 -0700 | [diff] [blame] | 37 | |
| 38 | static inline sk_sp<SkImage> decode_file(const char filename[]) { |
| 39 | sk_sp<SkData> data(SkData::MakeFromFileName(filename)); |
| 40 | return data ? SkImage::MakeFromEncoded(data) : nullptr; |
| 41 | } |
Hal Canary | 03a7f5f | 2017-02-10 09:06:38 -0500 | [diff] [blame] | 42 | #endif // DecodeFile_DEFINED |