1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
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
16 #include "png.h"
17 #include "rs_graphic_log.h"
18 #include "rs_graphic_test_utils.h"
19
WriteToPng(const std::string & filename,const WriteToPngParam & param)20 static bool WriteToPng(const std::string &filename, const WriteToPngParam ¶m)
21 {
22 if (filename.empty()) {
23 LOGI("RSBaseRenderUtil::WriteToPng filename is empty");
24 return false;
25 }
26 LOGI("RSBaseRenderUtil::WriteToPng filename = %{public}s", filename.c_str());
27 png_structp pngStruct = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
28 if (pngStruct == nullptr) {
29 return false;
30 }
31 png_infop pngInfo = png_create_info_struct(pngStruct);
32 if (pngInfo == nullptr) {
33 png_destroy_write_struct(&pngStruct, nullptr);
34 return false;
35 }
36
37 FILE *fp = fopen(filename.c_str(), "wb");
38 if (fp == nullptr) {
39 png_destroy_write_struct(&pngStruct, &pngInfo);
40 LOGE("WriteToPng file: %s open file failed, errno: %d", filename.c_str(), errno);
41 return false;
42 }
43 png_init_io(pngStruct, fp);
44
45 // set png header
46 png_set_IHDR(pngStruct, pngInfo,
47 param.width, param.height,
48 param.bitDepth,
49 PNG_COLOR_TYPE_RGBA,
50 PNG_INTERLACE_NONE,
51 PNG_COMPRESSION_TYPE_BASE,
52 PNG_FILTER_TYPE_BASE);
53 png_set_packing(pngStruct); // set packing info
54 png_write_info(pngStruct, pngInfo); // write to header
55
56 for (uint32_t i = 0; i < param.height; i++) {
57 png_write_row(pngStruct, param.data + (i * param.stride));
58 }
59 png_write_end(pngStruct, pngInfo);
60
61 // free
62 png_destroy_write_struct(&pngStruct, &pngInfo);
63 int ret = fclose(fp);
64 return ret == 0;
65 }
66
WriteToPngWithPixelMap(const std::string & fileName,OHOS::Media::PixelMap & pixelMap)67 bool WriteToPngWithPixelMap(const std::string& fileName, OHOS::Media::PixelMap& pixelMap)
68 {
69 constexpr int bitDepth = 8;
70
71 WriteToPngParam param;
72 param.width = static_cast<uint32_t>(pixelMap.GetWidth());
73 param.height = static_cast<uint32_t>(pixelMap.GetHeight());
74 param.data = pixelMap.GetPixels();
75 param.stride = static_cast<uint32_t>(pixelMap.GetRowBytes());
76 param.bitDepth = bitDepth;
77 return WriteToPng(fileName, param);
78 }
79
WaitTimeout(int ms)80 void WaitTimeout(int ms)
81 {
82 auto time = std::chrono::milliseconds(ms);
83 std::this_thread::sleep_for(time);
84 }
85