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