• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2022 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "gfxstream/ImageUtils.h"
16 
17 #include <stb/stb_image.h>
18 #include <stb/stb_image_write.h>
19 
20 #include <cstring>
21 
22 namespace gfxstream {
23 
LoadRGBAFromPng(const std::string & filename,uint32_t * outWidth,uint32_t * outHeight,std::vector<uint32_t> * outPixels)24 bool LoadRGBAFromPng(const std::string& filename, uint32_t* outWidth, uint32_t* outHeight,
25                      std::vector<uint32_t>* outPixels) {
26     *outWidth = 0;
27     *outHeight = 0;
28     outPixels->clear();
29 
30     int decodedWidth;
31     int decodedHeight;
32     int decodedChannels;
33     unsigned char* decodedPixels =
34         stbi_load(filename.c_str(), &decodedWidth, &decodedHeight, &decodedChannels,
35                   /*desiredChannels=*/4);
36     if (decodedPixels == nullptr) {
37         return false;
38     }
39 
40     const std::size_t decodedSize = decodedWidth * decodedHeight;
41     const std::size_t decodedSizeBytes = decodedSize * 4;
42 
43     *outWidth = static_cast<uint32_t>(decodedWidth);
44     *outHeight = static_cast<uint32_t>(decodedHeight);
45     outPixels->resize(decodedSize, 0);
46     std::memcpy(outPixels->data(), decodedPixels, decodedSizeBytes);
47 
48     stbi_image_free(decodedPixels);
49 
50     return true;
51 }
52 
SaveRGBAToPng(uint32_t width,uint32_t height,const uint32_t * pixels,const std::string & filename)53 bool SaveRGBAToPng(uint32_t width, uint32_t height, const uint32_t* pixels,
54                    const std::string& filename) {
55     if (stbi_write_png(filename.c_str(), width, height,
56                        /*channels=*/4, pixels, width * 4) == 0) {
57         return false;
58     }
59     return true;
60 }
61 
62 }  // namespace gfxstream
63