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 "core/components_ng/pattern/canvas/custom_paint_util.h"
17 #include "base/utils/string_utils.h"
18 
19 namespace OHOS::Ace::NG {
20 
21 // If type is empty or invalid format, use default: "image/png"
GetMimeType(const std::string & type)22 std::string GetMimeType(const std::string& type)
23 {
24     // type example: ["image/png"]
25     std::string str = type;
26     // convert to lowercase string, e.g. "image/png"
27     std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { return std::tolower(c); });
28     return str;
29 }
30 
GetQuality(const std::string & type,const double quality)31 double GetQuality(const std::string& type, const double quality)
32 {
33     // type example: "image/jpeg", quality example: 0.8
34     double qua = quality;
35     if (type != IMAGE_JPEG && type != IMAGE_WEBP) {
36         qua =  DEFAULT_QUALITY;
37     }
38     if (quality < 0.0 || quality > 1.0) {
39         qua =  DEFAULT_QUALITY;
40     }
41     return qua * QUALITY_COEFFICIENT;
42 }
43 
44 #ifndef ACE_UNITTEST
EncodeImage(std::string & type,const double quality,SkPixmap & src,SkDynamicMemoryWStream & dst)45 bool EncodeImage(std::string& type, const double quality, SkPixmap& src, SkDynamicMemoryWStream& dst)
46 {
47     bool encodeImageResult = false;
48     if (type == IMAGE_JPEG) {
49         SkJpegEncoder::Options options;
50         options.fQuality = quality;
51         encodeImageResult = SkJpegEncoder::Encode(&dst, src, options);
52     } else if (type == IMAGE_WEBP) {
53         SkWebpEncoder::Options options;
54         options.fQuality = quality;
55         encodeImageResult = SkWebpEncoder::Encode(&dst, src, options);
56     } else {
57         type = IMAGE_PNG;
58         SkPngEncoder::Options options;
59         encodeImageResult = SkPngEncoder::Encode(&dst, src, options);
60     }
61     return encodeImageResult;
62 }
63 #endif
64 } // namespace OHOS::Ace::NG
65