diff --git a/frameworks/innerkitsimpl/codec/src/image_source.cpp b/frameworks/innerkitsimpl/codec/src/image_source.cpp old mode 100644 new mode 100755 index 9dafd726244ab5bd6e85d3348793bc308f75c110..25af2eaadf284829c9b6e9b99ce8b999791e847c --- a/frameworks/innerkitsimpl/codec/src/image_source.cpp +++ b/frameworks/innerkitsimpl/codec/src/image_source.cpp @@ -217,6 +217,30 @@ unique_ptr ImageSource::CreateImageSource(const std::string &pathNa return unique_ptr(sourcePtr); } +unique_ptr ImageSource::CreateImageSource(const int fd, const SourceOptions &opts, + uint32_t &errorCode) +{ +#if !defined(_WIN32) && !defined(_APPLE) + StartTrace(BYTRACE_TAG_ZIMAGE, "CreateImageSource by fd"); +#endif + unique_ptr streamPtr = FileSourceStream::CreateSourceStream(fd); + if (streamPtr == nullptr) { + IMAGE_LOGE("[ImageSource]failed to create file source stream."); + errorCode = ERR_IMAGE_SOURCE_DATA; + return nullptr; + } + ImageSource *sourcePtr = new (std::nothrow) ImageSource(std::move(streamPtr), opts); + if (sourcePtr == nullptr) { + IMAGE_LOGE("[ImageSource]failed to create ImageSource by fd."); + errorCode = ERR_IMAGE_SOURCE_DATA; + return nullptr; + } + errorCode = SUCCESS; +#if !defined(_WIN32) && !defined(_APPLE) + FinishTrace(BYTRACE_TAG_ZIMAGE); +#endif + return unique_ptr(sourcePtr); +} unique_ptr ImageSource::CreateIncrementalImageSource(const IncrementalSourceOptions &opts, uint32_t &errorCode) { @@ -527,6 +551,22 @@ uint32_t ImageSource::GetImagePropertyInt(uint32_t index, const std::string &key return SUCCESS; } +uint32_t ImageSource::GetImagePropertyString(uint32_t index, const std::string &key, std::string &value) +{ + std::unique_lock guard(decodingMutex_); + uint32_t ret; + auto iter = GetValidImageStatus(0, ret); + if (iter == imageStatusMap_.end()) { + IMAGE_LOGE("[ImageSource]get valid image status fail on get image property, ret:%{public}u.", ret); + return ret; + } + ret = mainDecoder_->GetImagePropertyString(index, key, value); + if (ret != SUCCESS) { + IMAGE_LOGE("[ImageSource] GetImagePropertyInt fail, ret:%{public}u", ret); + return ret; + } + return SUCCESS; +} const SourceInfo &ImageSource::GetSourceInfo(uint32_t &errorCode) { std::lock_guard guard(decodingMutex_); @@ -694,6 +734,7 @@ uint32_t ImageSource::GetEncodedFormat(const string &formatHint, string &format) return SUCCESS; } else if (ret == ERR_IMAGE_SOURCE_DATA_INCOMPLETE) { streamIncomplete = true; + IMAGE_LOGE("[ImageSource]image source data error ERR_IMAGE_SOURCE_DATA_INCOMPLETE."); } } diff --git a/frameworks/innerkitsimpl/common/src/pixel_map.cpp b/frameworks/innerkitsimpl/common/src/pixel_map.cpp index e5d3b905041b854966830e36abbd551331edee82..b46fe6a2eb39c3dcc19c4a3c878d79a7f7135a4d 100644 --- a/frameworks/innerkitsimpl/common/src/pixel_map.cpp +++ b/frameworks/innerkitsimpl/common/src/pixel_map.cpp @@ -1085,7 +1085,7 @@ bool PixelMap::WriteImageData(Parcel &parcel, size_t size) const return false; } void *ptr = ::mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - + if (ptr == MAP_FAILED) { return false; } @@ -1162,7 +1162,6 @@ uint8_t *PixelMap::ReadImageData(Parcel &parcel, int32_t bufferSize) ReleaseMemory(AllocatorType::SHARE_MEM_ALLOC, ptr, &fd, bufferSize); #endif } - return base; } @@ -1235,7 +1234,7 @@ bool PixelMap::Marshalling(Parcel &parcel) const HiLog::Error(LABEL, "write image info to parcel failed."); return false; } - + if (!parcel.WriteInt32(static_cast(allocatorType_))) { HiLog::Error(LABEL, "write pixel map allocator type:[%{public}d] to parcel failed.", allocatorType_); @@ -1291,7 +1290,7 @@ PixelMap *PixelMap::Unmarshalling(Parcel &parcel) HiLog::Error(LABEL, "read imageInfo fail"); return nullptr; } - + AllocatorType allocType = static_cast(parcel.ReadInt32()); int32_t bufferSize = parcel.ReadInt32(); uint8_t *base = nullptr; diff --git a/frameworks/innerkitsimpl/stream/include/file_source_stream.h b/frameworks/innerkitsimpl/stream/include/file_source_stream.h index dced8d8458eb079f73ab4bc251fa7e948d5c6594..21e5b95a54524a5c41427055010c0428e6d97e69 100644 --- a/frameworks/innerkitsimpl/stream/include/file_source_stream.h +++ b/frameworks/innerkitsimpl/stream/include/file_source_stream.h @@ -27,6 +27,7 @@ namespace Media { class FileSourceStream : public SourceStream { public: static std::unique_ptr CreateSourceStream(const std::string &pathName); + static std::unique_ptr CreateSourceStream(const int fd); ~FileSourceStream(); bool Read(uint32_t desiredSize, ImagePlugin::DataStreamBuffer &outData) override; diff --git a/frameworks/innerkitsimpl/stream/src/file_source_stream.cpp b/frameworks/innerkitsimpl/stream/src/file_source_stream.cpp index ffe15f051395ae04273d9232f87ea7c21b0af0e0..0975a109797ac5f893a6a6da447cd88cc99ee461 100644 --- a/frameworks/innerkitsimpl/stream/src/file_source_stream.cpp +++ b/frameworks/innerkitsimpl/stream/src/file_source_stream.cpp @@ -13,7 +13,6 @@ * limitations under the License. */ -#include #include "directory_ex.h" #include "file_source_stream.h" #include "image_log.h" @@ -50,7 +49,27 @@ unique_ptr FileSourceStream::CreateSourceStream(const string & } FILE *filePtr = fopen(realPath.c_str(), "rb"); if (filePtr == nullptr) { - IMAGE_LOGE("[FileSourceStream]open file fail, error:%{public}s.", strerror(errno)); + IMAGE_LOGE("[FileSourceStream]open file fail."); + return nullptr; + } + long offset = ftell(filePtr); + if (offset < 0) { + IMAGE_LOGE("[FileSourceStream]get the position fail."); + fclose(filePtr); + return nullptr; + } + return (unique_ptr(new FileSourceStream(filePtr, size, offset, offset))); +} +unique_ptr FileSourceStream::CreateSourceStream(const int fd) +{ + size_t size = 0; + if (!ImageUtils::GetFileSize(fd, size)) { + IMAGE_LOGE("[FileSourceStream]get the file size fail."); + return nullptr; + } + FILE *filePtr = fdopen(fd, "rb"); + if (filePtr == nullptr) { + IMAGE_LOGE("[FileSourceStream]open file fail."); return nullptr; } long offset = ftell(filePtr); diff --git a/frameworks/innerkitsimpl/test/BUILD.gn b/frameworks/innerkitsimpl/test/BUILD.gn index 72f3d28a70af59b594f2df1e6b104831d8ae70c6..25372dba8a5eecc3e604dfb8ec4bf209f2072336 100644 --- a/frameworks/innerkitsimpl/test/BUILD.gn +++ b/frameworks/innerkitsimpl/test/BUILD.gn @@ -39,36 +39,38 @@ ohos_unittest("imagepixelmaptest") { # external_deps = [ "hiviewdfx_hilog_native:libhilog" ] } -#ohos_unittest("imagepixelmapparceltest") { -# module_out_path = module_output_path - -# include_dirs = [ -# "//foundation/multimedia/image_standard/interfaces/innerkits/include", -# "//foundation/multimedia/utils/include", -# "//third_party/googletest/googletest/include", -# "//utils/native/base/include", -# "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", -# "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", -# "//foundation/multimedia/image_standard/mock/native/include", -# ] -# sources = [ "./unittest/image_pixel_map_parcel_test.cpp" ] - -# deps = [ -# "//third_party/googletest:gmock_main", -# "//third_party/googletest:gtest_main", -# "//utils/native/base:utils", -# "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", -# "//foundation/multimedia/image_standard:image_framework", -# "//foundation/multimedia/image_standard/mock/native:utils_mock_static", -# "//foundation/multimedia/image_standard/mock/native:log_mock_static", -# ] -# external_deps = [ -# "bytrace_standard:bytrace_core", -# "hiviewdfx_hilog_native:libhilog", -# "ipc:ipc_core", -# "multimedia_image:libimage", -# ] -#} +ohos_unittest("imagepixelmapparceltest") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/multimedia/image_standard/interfaces/innerkits/include", + "//foundation/multimedia/utils/include", + "//third_party/googletest/googletest/include", + "//utils/native/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/multimedia/image_standard/mock/native/include", + ] + sources = [ "./unittest/image_pixel_map_parcel_test.cpp" ] + + deps = [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + + # "//foundation/multimedia/image_standard/mock/native:utils_mock_static", + # "//foundation/multimedia/image_standard/mock/native:log_mock_static", + ] + external_deps = [ + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + + #"//foundation/multimedia/image_standard/interfaces/innerkits:image_native", + ] +} ohos_unittest("imagesourcetest") { DUAL_ADAPTER = true @@ -84,17 +86,19 @@ ohos_unittest("imagesourcetest") { "//foundation/multimedia/image_standard/plugins/manager/include", ] sources = [ - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/test/unittest/image_source_gif_test.cpp", + # "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/test/unittest/image_source_gif_test.cpp", "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/test/unittest/image_source_jpeg_test.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/test/unittest/image_source_png_test.cpp", + + # "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/test/unittest/image_source_png_test.cpp", "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/test/unittest/image_source_util.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/test/unittest/image_source_webp_test.cpp", + + # "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/test/unittest/image_source_webp_test.cpp", ] if (DUAL_ADAPTER) { sources += [ "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/test/unittest/image_source_bmp_test.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/test/unittest/image_source_raw_test.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/test/unittest/image_source_wbmp_test.cpp", + # "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/test/unittest/image_source_raw_test.cpp", + # "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/test/unittest/image_source_wbmp_test.cpp", ] } @@ -165,8 +169,7 @@ group("unittest") { testonly = true deps = [ ":colorconvertertest", - - # ":imagepixelmapparceltest", + ":imagepixelmapparceltest", ":imagepixelmaptest", ":imagesourcetest", ":transformtest", diff --git a/frameworks/innerkitsimpl/test/unittest/image_pixel_map_test.cpp b/frameworks/innerkitsimpl/test/unittest/image_pixel_map_test.cpp index cbd34f6fd14f0c6196eeeda87563b77ea6c9b445..dc3fd6dc0c9d09ac018e198e5ed15aff4c0b07f2 100644 --- a/frameworks/innerkitsimpl/test/unittest/image_pixel_map_test.cpp +++ b/frameworks/innerkitsimpl/test/unittest/image_pixel_map_test.cpp @@ -83,7 +83,7 @@ public: if (bufferSize <= 0) { return nullptr; } - std::unique_ptr buffer = malloc(bufferSize); + void *buffer = malloc(bufferSize); if (buffer == nullptr) { return nullptr; } diff --git a/frameworks/innerkitsimpl/test/unittest/image_source_bmp_test.cpp b/frameworks/innerkitsimpl/test/unittest/image_source_bmp_test.cpp index 9bfb0724fdc64ecf1f6cb039f09c94d4ae1184fb..d77d15c615e83cc00f154ea6fec244b1a9da6ff3 100644 --- a/frameworks/innerkitsimpl/test/unittest/image_source_bmp_test.cpp +++ b/frameworks/innerkitsimpl/test/unittest/image_source_bmp_test.cpp @@ -19,6 +19,7 @@ #include "hilog/log.h" #include "image_packer.h" #include "image_source.h" +#include "image_source_util.h" #include "image_type.h" #include "image_utils.h" #include "media_errors.h" @@ -27,17 +28,15 @@ using namespace testing::ext; using namespace OHOS::Media; using namespace OHOS::HiviewDFX; +using namespace OHOS::ImageSourceUtil; -static const std::string IMAGE_INPUT_BMP_PATH = "/sdcard/multimedia/image/test.bmp"; +static const std::string IMAGE_INPUT_BMP_PATH = "/data/local/tmp/image/test.bmp"; static const std::string IMAGE_OUTPUT_BMP_FILE_PATH = "/data/test/test_bmp_file.jpg"; -int64_t PackImage(const std::string &filePath, std::unique_ptr pixelMap); -bool ReadFileToBuffer(const std::string &filePath, uint8_t *buffer, size_t bufferSize); - class ImageSourceBmpTest : public testing::Test { public: - ImageSourceBmpTest(){}; - ~ImageSourceBmpTest(){}; + ImageSourceBmpTest() {}; + ~ImageSourceBmpTest() {}; }; /** diff --git a/frameworks/innerkitsimpl/test/unittest/image_source_gif_test.cpp b/frameworks/innerkitsimpl/test/unittest/image_source_gif_test.cpp index 5b3c0d45a34be6f621461518370ddc8f7dd888a2..d45ddae68f7d4641117c9e3a3f0913c8f6ff4498 100644 --- a/frameworks/innerkitsimpl/test/unittest/image_source_gif_test.cpp +++ b/frameworks/innerkitsimpl/test/unittest/image_source_gif_test.cpp @@ -19,6 +19,7 @@ #include "hilog/log.h" #include "image_packer.h" #include "image_source.h" +#include "image_source_util.h" #include "image_type.h" #include "image_utils.h" #include "incremental_pixel_map.h" @@ -40,8 +41,8 @@ bool ReadFileToBuffer(const std::string &filePath, uint8_t *buffer, size_t buffe class ImageSourceGifTest : public testing::Test { public: - ImageSourceGifTest(){}; - ~ImageSourceGifTest(){}; + ImageSourceGifTest() {}; + ~ImageSourceGifTest() {}; }; /** @@ -59,7 +60,7 @@ HWTEST_F(ImageSourceGifTest, GifImageDecode001, TestSize.Level3) SourceOptions opts; opts.formatHint = "image/gif"; std::unique_ptr imageSource = - ImageSource::CreateImageSource("/sdcard/multimedia/image/test.gif", opts, errorCode); + ImageSource::CreateImageSource("/data/local/tmp/image/test.gif", opts, errorCode); ASSERT_EQ(errorCode, SUCCESS); ASSERT_NE(imageSource.get(), nullptr); /** @@ -119,7 +120,7 @@ HWTEST_F(ImageSourceGifTest, GifImageDecode002, TestSize.Level3) uint32_t errorCode = 0; SourceOptions opts; std::unique_ptr imageSource = - ImageSource::CreateImageSource("/sdcard/multimedia/image/test.gif", opts, errorCode); + ImageSource::CreateImageSource("/data/local/tmp/image/test.gif", opts, errorCode); ASSERT_EQ(errorCode, SUCCESS); ASSERT_NE(imageSource.get(), nullptr); /** @@ -146,7 +147,7 @@ HWTEST_F(ImageSourceGifTest, GifImageDecode003, TestSize.Level3) SourceOptions opts; opts.formatHint = "image/gif"; std::unique_ptr imageSource = - ImageSource::CreateImageSource("/sdcard/multimedia/image/gif/test.gif", opts, errorCode); + ImageSource::CreateImageSource("/data/local/tmp/image/gif/test.gif", opts, errorCode); ASSERT_EQ(errorCode, ERR_IMAGE_SOURCE_DATA); ASSERT_EQ(imageSource.get(), nullptr); } @@ -163,11 +164,11 @@ HWTEST_F(ImageSourceGifTest, GifImageDecode004, TestSize.Level3) * @tc.expected: step1. create image source success. */ size_t bufferSize = 0; - bool ret = ImageUtils::GetFileSize("/sdcard/multimedia/image/test.gif", bufferSize); + bool ret = ImageUtils::GetFileSize("/data/local/tmp/image/test.gif", bufferSize); ASSERT_EQ(ret, true); uint8_t *buffer = (uint8_t *)malloc(bufferSize); ASSERT_NE(buffer, nullptr); - ret = ReadFileToBuffer("/sdcard/multimedia/image/test.gif", buffer, bufferSize); + ret = ReadFileToBuffer("/data/local/tmp/image/test.gif", buffer, bufferSize); ASSERT_EQ(ret, true); uint32_t errorCode = 0; SourceOptions opts; @@ -216,7 +217,7 @@ HWTEST_F(ImageSourceGifTest, GifImageDecode005, TestSize.Level3) * @tc.expected: step1. create image source success. */ std::unique_ptr fs = std::make_unique(); - fs->open("/sdcard/multimedia/image/test.gif", std::fstream::binary | std::fstream::in); + fs->open("/data/local/tmp/image/test.gif", std::fstream::binary | std::fstream::in); bool isOpen = fs->is_open(); ASSERT_EQ(isOpen, true); uint32_t errorCode = 0; @@ -266,7 +267,7 @@ HWTEST_F(ImageSourceGifTest, GifImageDecode006, TestSize.Level3) SourceOptions opts; opts.formatHint = "image/gif"; std::unique_ptr imageSource = - ImageSource::CreateImageSource("/sdcard/multimedia/image/moving_test.gif", opts, errorCode); + ImageSource::CreateImageSource("/data/local/tmp/image/moving_test.gif", opts, errorCode); ASSERT_EQ(errorCode, SUCCESS); ASSERT_NE(imageSource.get(), nullptr); /** @@ -325,11 +326,11 @@ HWTEST_F(ImageSourceGifTest, GifImageDecode007, TestSize.Level3) * @tc.expected: step1. create image source success. */ size_t bufferSize = 0; - bool fileRet = ImageUtils::GetFileSize("/sdcard/multimedia/image/moving_test.gif", bufferSize); + bool fileRet = ImageUtils::GetFileSize("/data/local/tmp/image/moving_test.gif", bufferSize); ASSERT_EQ(fileRet, true); uint8_t *buffer = (uint8_t *)malloc(bufferSize); ASSERT_NE(buffer, nullptr); - fileRet = ReadFileToBuffer("/sdcard/multimedia/image/moving_test.gif", buffer, bufferSize); + fileRet = ReadFileToBuffer("/data/local/tmp/image/moving_test.gif", buffer, bufferSize); ASSERT_EQ(fileRet, true); uint32_t errorCode = 0; IncrementalSourceOptions incOpts; diff --git a/frameworks/innerkitsimpl/test/unittest/image_source_png_test.cpp b/frameworks/innerkitsimpl/test/unittest/image_source_png_test.cpp index 9ef973f91a4ab992d1014db0bd48e2d805337c4e..436f9910d0538030e2c10cab1e159ef1c7bf8561 100644 --- a/frameworks/innerkitsimpl/test/unittest/image_source_png_test.cpp +++ b/frameworks/innerkitsimpl/test/unittest/image_source_png_test.cpp @@ -19,6 +19,7 @@ #include "hilog/log.h" #include "image_packer.h" #include "image_source.h" +#include "image_source_util.h" #include "image_type.h" #include "image_utils.h" #include "incremental_pixel_map.h" @@ -40,8 +41,8 @@ bool ReadFileToBuffer(const std::string &filePath, uint8_t *buffer, size_t buffe class ImageSourcePngTest : public testing::Test { public: - ImageSourcePngTest(){}; - ~ImageSourcePngTest(){}; + ImageSourcePngTest() {}; + ~ImageSourcePngTest() {}; }; /** @@ -59,7 +60,7 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode001, TestSize.Level3) SourceOptions opts; opts.formatHint = "image/png"; std::unique_ptr imageSource = - ImageSource::CreateImageSource("/sdcard/multimedia/image/test.png", opts, errorCode); + ImageSource::CreateImageSource("/data/local/tmp/image/test.png", opts, errorCode); ASSERT_EQ(errorCode, SUCCESS); ASSERT_NE(imageSource.get(), nullptr); /** @@ -75,7 +76,7 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode001, TestSize.Level3) * @tc.steps: step3. compress the pixel map to png file. * @tc.expected: step3. pack pixel map success and the png compress file size equals to PNG_PACK_SIZE. */ - int64_t packSize = PackImage("/sdcard/multimedia/image/test_file.png", std::move(pixelMap)); + int64_t packSize = PackImage("/data/local/tmp/image/test_file.png", std::move(pixelMap)); ASSERT_NE(packSize, 0); } @@ -93,7 +94,7 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode002, TestSize.Level3) uint32_t errorCode = 0; SourceOptions opts; std::unique_ptr imageSource = - ImageSource::CreateImageSource("/sdcard/multimedia/image/test.png", opts, errorCode); + ImageSource::CreateImageSource("/data/local/tmp/image/test.png", opts, errorCode); ASSERT_EQ(errorCode, SUCCESS); ASSERT_NE(imageSource.get(), nullptr); } @@ -113,7 +114,7 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode003, TestSize.Level3) SourceOptions opts; opts.formatHint = "image/png"; std::unique_ptr imageSource = - ImageSource::CreateImageSource("/sdcard/multimedia/image/test.png", opts, errorCode); + ImageSource::CreateImageSource("/data/local/tmp/image/test.png", opts, errorCode); ASSERT_EQ(errorCode, SUCCESS); ASSERT_NE(imageSource.get(), nullptr); } @@ -132,7 +133,7 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode004, TestSize.Level3) uint32_t errorCode = 0; SourceOptions opts; std::unique_ptr imageSource = - ImageSource::CreateImageSource("/sdcard/multimedia/image/png/test.png", opts, errorCode); + ImageSource::CreateImageSource("/data/local/tmp/image/png/test.png", opts, errorCode); ASSERT_EQ(errorCode, ERR_IMAGE_SOURCE_DATA); ASSERT_EQ(imageSource.get(), nullptr); } @@ -149,11 +150,11 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode005, TestSize.Level3) * @tc.expected: step1. create image source success. */ size_t bufferSize = 0; - bool ret = ImageUtils::GetFileSize("/sdcard/multimedia/image/test.png", bufferSize); + bool ret = ImageUtils::GetFileSize("/data/local/tmp/image/test.png", bufferSize); ASSERT_EQ(ret, true); uint8_t *buffer = (uint8_t *)malloc(bufferSize); ASSERT_NE(buffer, nullptr); - ret = ReadFileToBuffer("/sdcard/multimedia/image/test.png", buffer, bufferSize); + ret = ReadFileToBuffer("/data/local/tmp/image/test.png", buffer, bufferSize); ASSERT_EQ(ret, true); uint32_t errorCode = 0; SourceOptions opts; @@ -173,7 +174,7 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode005, TestSize.Level3) * @tc.steps: step3. compress the pixel map to jpeg file. * @tc.expected: step3. pack pixel map success and the jpeg compress file size equals to PNG_PACK_SIZE. */ - int64_t packSize = PackImage("/sdcard/multimedia/image/test_file.jpg", std::move(pixelMap)); + int64_t packSize = PackImage("/data/local/tmp/image/test_file.jpg", std::move(pixelMap)); ASSERT_NE(packSize, 0); free(buffer); } @@ -190,7 +191,7 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode006, TestSize.Level3) * @tc.expected: step1. create image source success. */ std::unique_ptr fs = std::make_unique(); - fs->open("/sdcard/multimedia/image/test.png", std::fstream::binary | std::fstream::in); + fs->open("/data/local/tmp/image/test.png", std::fstream::binary | std::fstream::in); bool isOpen = fs->is_open(); ASSERT_EQ(isOpen, true); uint32_t errorCode = 0; @@ -227,11 +228,11 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode007, TestSize.Level3) * @tc.expected: step1. create image source success. */ size_t bufferSize = 0; - bool fileRet = ImageUtils::GetFileSize("/sdcard/multimedia/image/test.png", bufferSize); + bool fileRet = ImageUtils::GetFileSize("/data/local/tmp/image/test.png", bufferSize); ASSERT_EQ(fileRet, true); uint8_t *buffer = (uint8_t *)malloc(bufferSize); ASSERT_NE(buffer, nullptr); - fileRet = ReadFileToBuffer("/sdcard/multimedia/image/test.png", buffer, bufferSize); + fileRet = ReadFileToBuffer("/data/local/tmp/image/test.png", buffer, bufferSize); ASSERT_EQ(fileRet, true); uint32_t errorCode = 0; IncrementalSourceOptions incOpts; @@ -272,7 +273,7 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode007, TestSize.Level3) * @tc.steps: step3. compress the pixel map to jpeg file. * @tc.expected: step3. pack pixel map success and the jpeg compress file size equals to PNG_PACK_SIZE. */ - int64_t packSize = PackImage("/sdcard/multimedia/image/test_file.jpg", std::move(incPixelMap)); + int64_t packSize = PackImage("/data/local/tmp/image/test_file.jpg", std::move(incPixelMap)); ASSERT_NE(packSize, 0); free(buffer); } @@ -291,7 +292,7 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode008, TestSize.Level3) uint32_t errorCode = 0; SourceOptions opts; std::unique_ptr imageSource = - ImageSource::CreateImageSource("/sdcard/multimedia/image/test.png", opts, errorCode); + ImageSource::CreateImageSource("/data/local/tmp/image/test.png", opts, errorCode); ASSERT_EQ(errorCode, SUCCESS); ASSERT_NE(imageSource.get(), nullptr); /** @@ -313,9 +314,9 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode008, TestSize.Level3) * @tc.steps: step4. compress the pixlel map to jpeg file. * @tc.expected: step4. pack pixel map success and the jpeg compress file size equals to PNG_PACK_SIZE. */ - int64_t packSize = PackImage("/sdcard/multimedia/image/test_png_file1.jpg", std::move(pixelMap1)); + int64_t packSize = PackImage("/data/local/tmp/image/test_png_file1.jpg", std::move(pixelMap1)); ASSERT_NE(packSize, 0); - packSize = PackImage("/sdcard/multimedia/image/test_png_file2.jpg", std::move(pixelMap2)); + packSize = PackImage("/data/local/tmp/image/test_png_file2.jpg", std::move(pixelMap2)); ASSERT_NE(packSize, 0); } @@ -331,11 +332,11 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode009, TestSize.Level3) * @tc.expected: step1. create image source success. */ size_t bufferSize = 0; - bool fileRet = ImageUtils::GetFileSize("/sdcard/multimedia/image/test.png", bufferSize); + bool fileRet = ImageUtils::GetFileSize("/data/local/tmp/image/test.png", bufferSize); ASSERT_EQ(fileRet, true); uint8_t *buffer = (uint8_t *)malloc(bufferSize); ASSERT_NE(buffer, nullptr); - fileRet = ReadFileToBuffer("/sdcard/multimedia/image/test.png", buffer, bufferSize); + fileRet = ReadFileToBuffer("/data/local/tmp/image/test.png", buffer, bufferSize); ASSERT_EQ(fileRet, true); uint32_t errorCode = 0; IncrementalSourceOptions incOpts; @@ -380,9 +381,9 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode009, TestSize.Level3) * @tc.steps: step4. compress the pixel map to jpeg file. * @tc.expected: step4. pack bitmap success and the jpeg compress file size equals to PNG_PACK_SIZE. */ - int64_t packSize = PackImage("/sdcard/multimedia/image/test_png_inc1.jpg", std::move(incPixelMap)); + int64_t packSize = PackImage("/data/local/tmp/image/test_png_inc1.jpg", std::move(incPixelMap)); ASSERT_NE(packSize, 0); - packSize = PackImage("/sdcard/multimedia/image/test_png_onetime1.jpg", std::move(pixelMap1)); + packSize = PackImage("/data/local/tmp/image/test_png_onetime1.jpg", std::move(pixelMap1)); ASSERT_NE(packSize, 0); free(buffer); } @@ -399,11 +400,11 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode010, TestSize.Level3) * @tc.expected: step1. create image source success. */ size_t bufferSize = 0; - bool fileRet = ImageUtils::GetFileSize("/sdcard/multimedia/image/test.png", bufferSize); + bool fileRet = ImageUtils::GetFileSize("/data/local/tmp/image/test.png", bufferSize); ASSERT_EQ(fileRet, true); uint8_t *buffer = (uint8_t *)malloc(bufferSize); ASSERT_NE(buffer, nullptr); - fileRet = ReadFileToBuffer("/sdcard/multimedia/image/test.png", buffer, bufferSize); + fileRet = ReadFileToBuffer("/data/local/tmp/image/test.png", buffer, bufferSize); ASSERT_EQ(fileRet, true); uint32_t errorCode = 0; IncrementalSourceOptions incOpts; @@ -453,9 +454,9 @@ HWTEST_F(ImageSourcePngTest, PngImageDecode010, TestSize.Level3) * @tc.steps: step4. compress the pixel map to jpeg file. * @tc.expected: step4. pack pixel map success and the jpeg compress file size equals to PNG_PACK_SIZE. */ - int64_t packSize = PackImage("/sdcard/multimedia/image/test_png_inc2.jpg", std::move(incPixelMap)); + int64_t packSize = PackImage("/data/local/tmp/image/test_png_inc2.jpg", std::move(incPixelMap)); ASSERT_NE(packSize, 0); - packSize = PackImage("/sdcard/multimedia/image/test_png_onetime2.jpg", std::move(pixelMap1)); + packSize = PackImage("/data/local/tmp/image/test_png_onetime2.jpg", std::move(pixelMap1)); ASSERT_NE(packSize, 0); free(buffer); } @@ -472,7 +473,7 @@ HWTEST_F(ImageSourcePngTest, PngImageCrop001, TestSize.Level3) * @tc.expected: step1. create png image source success. */ std::unique_ptr fs = std::make_unique(); - fs->open("/sdcard/multimedia/image/test.png", std::fstream::binary | std::fstream::in); + fs->open("/data/local/tmp/image/test.png", std::fstream::binary | std::fstream::in); bool isOpen = fs->is_open(); ASSERT_EQ(isOpen, true); uint32_t errorCode = 0; @@ -508,7 +509,7 @@ HWTEST_F(ImageSourcePngTest, PngNinePatch001, TestSize.Level3) * @tc.expected: step1. create png image source success. */ std::unique_ptr fs = std::make_unique(); - fs->open("/sdcard/multimedia/image/test.9.png", std::fstream::binary | std::fstream::in); + fs->open("/data/local/tmp/image/test.9.png", std::fstream::binary | std::fstream::in); bool isOpen = fs->is_open(); ASSERT_EQ(isOpen, true); uint32_t errorCode = 0; @@ -544,7 +545,7 @@ HWTEST_F(ImageSourcePngTest, PngNinePatch002, TestSize.Level3) * @tc.expected: step1. create png image source success. */ std::unique_ptr fs = std::make_unique(); - fs->open("/sdcard/multimedia/image/test.png", std::fstream::binary | std::fstream::in); + fs->open("/data/local/tmp/image/test.png", std::fstream::binary | std::fstream::in); bool isOpen = fs->is_open(); ASSERT_EQ(isOpen, true); uint32_t errorCode = 0; @@ -579,7 +580,7 @@ HWTEST_F(ImageSourcePngTest, PngNinePatch003, TestSize.Level3) * @tc.expected: step1. create png image source success. */ std::unique_ptr fs = std::make_unique(); - fs->open("/sdcard/multimedia/image/test.9.png", std::fstream::binary | std::fstream::in); + fs->open("/data/local/tmp/image/test.9.png", std::fstream::binary | std::fstream::in); bool isOpen = fs->is_open(); ASSERT_EQ(isOpen, true); uint32_t errorCode = 0; diff --git a/frameworks/innerkitsimpl/test/unittest/image_source_raw_test.cpp b/frameworks/innerkitsimpl/test/unittest/image_source_raw_test.cpp index b12ddca612699a50d509976b9754225ef5c493ae..867c500f6b5578829b1b8e928abfd2e4257c6b7a 100644 --- a/frameworks/innerkitsimpl/test/unittest/image_source_raw_test.cpp +++ b/frameworks/innerkitsimpl/test/unittest/image_source_raw_test.cpp @@ -29,13 +29,13 @@ using namespace testing::ext; using namespace OHOS::Media; using namespace OHOS::HiviewDFX; -static const std::string IMAGE_INPUT_DNG_PATH = "/sdcard/multimedia/image/test.dng"; +static const std::string IMAGE_INPUT_DNG_PATH = "/data/local/tmp/image/test.dng"; static const std::string IMAGE_OUTPUT_DNG_FILE_PATH = "/data/test/test_raw_file.jpg"; class ImageSourceRawTest : public testing::Test { public: - ImageSourceRawTest(){}; - ~ImageSourceRawTest(){}; + ImageSourceRawTest() {}; + ~ImageSourceRawTest() {}; }; /** @@ -68,7 +68,7 @@ HWTEST_F(ImageSourceRawTest, RawImageDecode001, TestSize.Level3) * @tc.steps: step3. compress the pixel map to jpeg file. * @tc.expected: step3. pack pixel map success and compare the jpeg compress file size. */ - int64_t packSize = PackImage(IMAGE_OUTPUT_DNG_FILE_PATH, std::move(pixelMap)); + int64_t packSize = OHOS::ImageSourceUtil::PackImage(IMAGE_OUTPUT_DNG_FILE_PATH, std::move(pixelMap)); ASSERT_NE(packSize, 0); } @@ -103,7 +103,7 @@ HWTEST_F(ImageSourceRawTest, RawImageDecode002, TestSize.Level3) * @tc.steps: step3. compress the pixel map to jpeg file. * @tc.expected: step3. pack pixel map success and compare the jpeg compress file size. */ - int64_t packSize = PackImage(IMAGE_OUTPUT_DNG_FILE_PATH, std::move(pixelMap)); + int64_t packSize = OHOS::ImageSourceUtil::PackImage(IMAGE_OUTPUT_DNG_FILE_PATH, std::move(pixelMap)); ASSERT_NE(packSize, 0); } @@ -167,7 +167,7 @@ HWTEST_F(ImageSourceRawTest, RawImageDecode004, TestSize.Level3) * @tc.steps: step3. compress the pixel map to jpeg file. * @tc.expected: step3. pack pixel map success and compare the jpeg compress file size. */ - int64_t packSize = PackImage(IMAGE_OUTPUT_DNG_FILE_PATH, std::move(pixelMap)); + int64_t packSize = OHOS::ImageSourceUtil::PackImage(IMAGE_OUTPUT_DNG_FILE_PATH, std::move(pixelMap)); ASSERT_NE(packSize, 0); } @@ -234,7 +234,7 @@ HWTEST_F(ImageSourceRawTest, RawImageDecode007, TestSize.Level3) ASSERT_EQ(ret, true); auto *buffer = (uint8_t *)malloc(bufferSize); ASSERT_NE(buffer, nullptr); - ret = ReadFileToBuffer(IMAGE_INPUT_DNG_PATH, buffer, bufferSize); + ret = OHOS::ImageSourceUtil::ReadFileToBuffer(IMAGE_INPUT_DNG_PATH, buffer, bufferSize); ASSERT_EQ(ret, true); uint32_t errorCode = 0; SourceOptions opts; @@ -263,7 +263,7 @@ HWTEST_F(ImageSourceRawTest, RawImageDecode007, TestSize.Level3) * @tc.expected: step3. pack pixel map success and compare the jpeg compress file size. */ ImagePacker imagePacker; - int64_t packSize = PackImage(IMAGE_OUTPUT_DNG_FILE_PATH, std::move(pixelMap)); + int64_t packSize = OHOS::ImageSourceUtil::PackImage(IMAGE_OUTPUT_DNG_FILE_PATH, std::move(pixelMap)); ASSERT_NE(packSize, 0); free(buffer); } @@ -299,7 +299,7 @@ HWTEST_F(ImageSourceRawTest, RawImageDecode008, TestSize.Level3) * @tc.steps: step3. compress the pixel map to jpeg file. * @tc.expected: step3. pack pixel map success and the jpeg compress file size. */ - int64_t packSize = PackImage(IMAGE_OUTPUT_DNG_FILE_PATH, std::move(pixelMap)); + int64_t packSize = OHOS::ImageSourceUtil::PackImage(IMAGE_OUTPUT_DNG_FILE_PATH, std::move(pixelMap)); ASSERT_NE(packSize, 0); } @@ -338,9 +338,9 @@ HWTEST_F(ImageSourceRawTest, RawImageDecode009, TestSize.Level3) * @tc.steps: step4. compress the pixel map to jpeg file. * @tc.expected: step4. pack pixel map success and compare the jpeg compress file size. */ - int64_t packSize = PackImage(IMAGE_OUTPUT_DNG_FILE_PATH, std::move(pixelMap1)); + int64_t packSize = OHOS::ImageSourceUtil::PackImage(IMAGE_OUTPUT_DNG_FILE_PATH, std::move(pixelMap1)); ASSERT_NE(packSize, 0); - packSize = PackImage(IMAGE_OUTPUT_DNG_FILE_PATH, std::move(pixelMap2)); + packSize = OHOS::ImageSourceUtil::PackImage(IMAGE_OUTPUT_DNG_FILE_PATH, std::move(pixelMap2)); ASSERT_NE(packSize, 0); } @@ -361,7 +361,7 @@ HWTEST_F(ImageSourceRawTest, RawImageDecode010, TestSize.Level3) ASSERT_EQ(ret, true); auto *buffer = (uint8_t *)malloc(bufferSize); ASSERT_NE(buffer, nullptr); - ret = ReadFileToBuffer(IMAGE_INPUT_DNG_PATH, buffer, bufferSize); + ret = OHOS::ImageSourceUtil::ReadFileToBuffer(IMAGE_INPUT_DNG_PATH, buffer, bufferSize); ASSERT_EQ(ret, true); buffer[0] = 43; uint32_t errorCode = 0; diff --git a/frameworks/innerkitsimpl/test/unittest/image_source_util.cpp b/frameworks/innerkitsimpl/test/unittest/image_source_util.cpp index 0dec028ea2b9471fe4c5dee33c2c274ced5f4411..162df9cc056bb700aed7c0acd321b2d4d888e336 100644 --- a/frameworks/innerkitsimpl/test/unittest/image_source_util.cpp +++ b/frameworks/innerkitsimpl/test/unittest/image_source_util.cpp @@ -27,15 +27,22 @@ using namespace OHOS::Media; using namespace OHOS::HiviewDFX; +using namespace OHOS::ImageSourceUtil; static constexpr OHOS::HiviewDFX::HiLogLabel LABEL_TEST = { LOG_CORE, LOG_TAG_DOMAIN_ID_IMAGE, "ImageSourceUtil" }; +namespace OHOS { +namespace ImageSourceUtil { +constexpr uint32_t NUM_1 = 1; +constexpr uint32_t NUM_100 = 100; +constexpr int64_t BUFFER_SIZE = 2 * 1024 * 1024; + int64_t PackImage(const std::string &filePath, std::unique_ptr pixelMap) { ImagePacker imagePacker; PackOption option; option.format = "image/jpeg"; - option.quality = 100; - option.numberHint = 1; + option.quality = NUM_100; + option.numberHint = NUM_1; std::set formats; uint32_t ret = imagePacker.GetSupportedFormats(formats); if (ret != SUCCESS) { @@ -50,6 +57,32 @@ int64_t PackImage(const std::string &filePath, std::unique_ptr pixelMa return packedSize; } +int64_t PackImage(std::unique_ptr imageSource) +{ + ImagePacker imagePacker; + PackOption option; + option.format = "image/jpeg"; + option.quality = NUM_100; + option.numberHint = 1; + std::set formats; + uint32_t ret = imagePacker.GetSupportedFormats(formats); + if (ret != SUCCESS) { + HiLog::Error(LABEL_TEST, "image packer get supported format failed, ret=%{public}u.", ret); + return 0; + } + int64_t bufferSize = BUFFER_SIZE; + uint8_t *resultBuffer = (uint8_t *)malloc(bufferSize); + if (resultBuffer == nullptr) { + HiLog::Error(LABEL_TEST, "image packer malloc buffer failed."); + return 0; + } + imagePacker.StartPacking(resultBuffer, bufferSize, option); + imagePacker.AddImage(*imageSource); + int64_t packedSize = 0; + imagePacker.FinalizePacking(packedSize); + HiLog::Debug(LABEL_TEST, "packedSize=%{public}lld.", static_cast(packedSize)); + return packedSize; +} bool ReadFileToBuffer(const std::string &filePath, uint8_t *buffer, size_t bufferSize) { std::string realPath; @@ -79,4 +112,6 @@ bool ReadFileToBuffer(const std::string &filePath, uint8_t *buffer, size_t buffe } fclose(fp); return true; -} \ No newline at end of file +} +} +} // namespace diff --git a/frameworks/innerkitsimpl/test/unittest/image_source_util.h b/frameworks/innerkitsimpl/test/unittest/image_source_util.h index abf59886889cb2e2b1571c95dec10a9885cc6105..b3647bffeb4e03997d5d564eb41bca52a0138f2d 100644 --- a/frameworks/innerkitsimpl/test/unittest/image_source_util.h +++ b/frameworks/innerkitsimpl/test/unittest/image_source_util.h @@ -17,9 +17,14 @@ #ifndef IMAGE_SOURCE_UTIL_H #define IMAGE_SOURCE_UTIL_H #include +#include "image_source.h" #include "pixel_map.h" +namespace OHOS { +namespace ImageSourceUtil { int64_t PackImage(const std::string &filePath, std::unique_ptr pixelMap); +int64_t PackImage(std::unique_ptr imageSource); bool ReadFileToBuffer(const std::string &filePath, uint8_t *buffer, size_t bufferSize); - +} +} #endif // IMAGE_SOURCE_UTIL_H \ No newline at end of file diff --git a/frameworks/innerkitsimpl/test/unittest/image_source_wbmp_test.cpp b/frameworks/innerkitsimpl/test/unittest/image_source_wbmp_test.cpp index 802a17b22e6612c8237233f93460db4c47170e3e..612dcfc06a6fcabc6d9284351cdec1b56bb9dd9d 100644 --- a/frameworks/innerkitsimpl/test/unittest/image_source_wbmp_test.cpp +++ b/frameworks/innerkitsimpl/test/unittest/image_source_wbmp_test.cpp @@ -30,12 +30,12 @@ using namespace testing::ext; using namespace OHOS::Media; using namespace OHOS::HiviewDFX; -static const std::string IMAGE_INPUT_WBMP_PATH = "/sdcard/multimedia/image/test.wbmp"; +static const std::string IMAGE_INPUT_WBMP_PATH = "/data/local/tmp/image/test.wbmp"; class ImageSourceWbmpTest : public testing::Test { public: - ImageSourceWbmpTest(){}; - ~ImageSourceWbmpTest(){}; + ImageSourceWbmpTest() {}; + ~ImageSourceWbmpTest() {}; }; /** @@ -216,7 +216,7 @@ HWTEST_F(ImageSourceWbmpTest, WbmpImageDecode007, TestSize.Level3) ASSERT_EQ(ret, true); auto *buffer = (uint8_t *)malloc(bufferSize); ASSERT_NE(buffer, nullptr); - ret = ReadFileToBuffer(IMAGE_INPUT_WBMP_PATH, buffer, bufferSize); + ret = OHOS::ImageSourceUtil::ReadFileToBuffer(IMAGE_INPUT_WBMP_PATH, buffer, bufferSize); ASSERT_EQ(ret, true); uint32_t errorCode = 0; SourceOptions opts; @@ -321,7 +321,7 @@ HWTEST_F(ImageSourceWbmpTest, WbmpImageDecode010, TestSize.Level3) ASSERT_EQ(ret, true); auto *buffer = (uint8_t *)malloc(bufferSize); ASSERT_NE(buffer, nullptr); - ret = ReadFileToBuffer(IMAGE_INPUT_WBMP_PATH, buffer, bufferSize); + ret = OHOS::ImageSourceUtil::ReadFileToBuffer(IMAGE_INPUT_WBMP_PATH, buffer, bufferSize); ASSERT_EQ(ret, true); buffer[0] = 43; uint32_t errorCode = 0; diff --git a/frameworks/innerkitsimpl/test/unittest/image_source_webp_test.cpp b/frameworks/innerkitsimpl/test/unittest/image_source_webp_test.cpp index fa1b8d0d8b9a291fa45db63c373d9bd1be14250b..64daab6cd9faadb6ec3c997693840f578bd7f72e 100644 --- a/frameworks/innerkitsimpl/test/unittest/image_source_webp_test.cpp +++ b/frameworks/innerkitsimpl/test/unittest/image_source_webp_test.cpp @@ -19,6 +19,7 @@ #include "hilog/log.h" #include "image_packer.h" #include "image_source.h" +#include "image_source_util.h" #include "image_type.h" #include "image_utils.h" #include "incremental_pixel_map.h" @@ -34,8 +35,8 @@ static constexpr OHOS::HiviewDFX::HiLogLabel LABEL_TEST = { LOG_CORE, LOG_TAG_DOMAIN_ID_IMAGE, "ImageSourceWebpTest" }; static constexpr uint32_t DEFAULT_DELAY_UTIME = 10000; // 10 ms. -static const std::string IMAGE_INPUT_WEBP_PATH = "/sdcard/multimedia/image/test_large.webp"; -static const std::string IMAGE_INPUT_HW_JPEG_PATH = "/sdcard/multimedia/image/test_hw.jpg"; +static const std::string IMAGE_INPUT_WEBP_PATH = "/data/local/tmp/image/test_large.webp"; +static const std::string IMAGE_INPUT_HW_JPEG_PATH = "/data/local/tmp/image/test_hw.jpg"; static const std::string IMAGE_OUTPUT_JPEG_FILE_PATH = "/data/test/test_webp_file.jpg"; static const std::string IMAGE_OUTPUT_JPEG_BUFFER_PATH = "/data/test/test_webp_buffer.jpg"; static const std::string IMAGE_OUTPUT_JPEG_ISTREAM_PATH = "/data/test/test_webp_istream.jpg"; @@ -52,8 +53,8 @@ bool ReadFileToBuffer(const std::string &filePath, uint8_t *buffer, size_t buffe class ImageSourceWebpTest : public testing::Test { public: - ImageSourceWebpTest(){}; - ~ImageSourceWebpTest(){}; + ImageSourceWebpTest() {}; + ~ImageSourceWebpTest() {}; }; /** @@ -508,7 +509,7 @@ HWTEST_F(ImageSourceWebpTest, WebpImageCrop001, TestSize.Level3) * @tc.expected: step1. create webp image source success. */ std::unique_ptr fs = std::make_unique(); - fs->open("/sdcard/multimedia/image/test_large.webp", std::fstream::binary | std::fstream::in); + fs->open("/data/local/tmp/image/test_large.webp", std::fstream::binary | std::fstream::in); bool isOpen = fs->is_open(); ASSERT_EQ(isOpen, true); uint32_t errorCode = 0; diff --git a/frameworks/innerkitsimpl/test/unittest/image_transform_test.cpp b/frameworks/innerkitsimpl/test/unittest/image_transform_test.cpp index f872a838b3f49fafccbeda0531781ecbb64025bd..09b5acd9c0e284bcc6c60da699f395900c8d4ad6 100644 --- a/frameworks/innerkitsimpl/test/unittest/image_transform_test.cpp +++ b/frameworks/innerkitsimpl/test/unittest/image_transform_test.cpp @@ -23,8 +23,8 @@ namespace OHOS { namespace Multimedia { class ImageTransformTest : public testing::Test { public: - ImageTransformTest(){}; - ~ImageTransformTest(){}; + ImageTransformTest() {}; + ~ImageTransformTest() {}; }; /* diff --git a/frameworks/innerkitsimpl/utils/include/image_utils.h b/frameworks/innerkitsimpl/utils/include/image_utils.h index ed94d6ac3160e5cfdf2f77e409d8794e0ff2b42b..eb70883557694682191ac98af54bcca2472fbfc5 100644 --- a/frameworks/innerkitsimpl/utils/include/image_utils.h +++ b/frameworks/innerkitsimpl/utils/include/image_utils.h @@ -29,6 +29,7 @@ const std::string IMAGE_ENCODE_FORMAT = "encodeFormat"; class ImageUtils { public: static bool GetFileSize(const std::string &pathName, size_t &size); + static bool GetFileSize(const int fd, size_t &size); static bool GetInputStreamSize(std::istream &inputStream, size_t &size); static int32_t GetPixelBytes(const PixelFormat &pixelFormat); static bool PathToRealPath(const std::string &path, std::string &realPath); diff --git a/frameworks/innerkitsimpl/utils/src/image_utils.cpp b/frameworks/innerkitsimpl/utils/src/image_utils.cpp index b1e5da791dbade49c47636aa01b26f85f2525565..e309bdb20d07eb34f245301bd3faa5a5dda8cad2 100644 --- a/frameworks/innerkitsimpl/utils/src/image_utils.cpp +++ b/frameworks/innerkitsimpl/utils/src/image_utils.cpp @@ -55,6 +55,18 @@ bool ImageUtils::GetFileSize(const string &pathName, size_t &size) return true; } +bool ImageUtils::GetFileSize(const int fd, size_t &size) +{ + struct stat statbuf; + int ret = fstat(fd, &statbuf); + if (ret != 0) { + IMAGE_LOGE("[ImageUtil]get the file size failed, ret:%{public}d.", ret); + return false; + } + size = statbuf.st_size; + return true; +} + bool ImageUtils::GetInputStreamSize(istream &inputStream, size_t &size) { if (inputStream.rdbuf() == nullptr) { diff --git a/frameworks/kits/js/common/image_packer_napi.cpp b/frameworks/kits/js/common/image_packer_napi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..66cb295e19b4870fa42689a93feecdfc1cccf35d --- /dev/null +++ b/frameworks/kits/js/common/image_packer_napi.cpp @@ -0,0 +1,381 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "image_packer_napi.h" +#include "hilog/log.h" +#include "media_errors.h" +#include "image_napi_utils.h" +#include "image_packer.h" +#include "image_source.h" +#include "image_source_napi.h" + +using OHOS::HiviewDFX::HiLog; +namespace { + constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, LOG_DOMAIN, "ImagePackerNapi"}; +} + +namespace OHOS { +namespace Media { +static const std::string CLASS_NAME_IMAGEPACKER = "ImagePacker"; +std::shared_ptr ImagePackerNapi::sImgPck_ = nullptr; +std::shared_ptr ImagePackerNapi::sImgSource_ = nullptr; +napi_ref ImagePackerNapi::sConstructor_ = nullptr; + +const int ARGS_THREE = 3; +const int PARAM0 = 0; +const int PARAM1 = 1; +const int PARAM2 = 2; +const int32_t SIZE = 100; + +struct ImagePackerAsyncContext { + napi_env env; + napi_async_work work; + napi_deferred deferred; + napi_ref callbackRef = nullptr; + ImagePackerNapi *constructor_; + bool status; + std::shared_ptr rImageSource; + PackOption packOption; + std::shared_ptr rImagePacker; + void *resultBuffer = nullptr; + int64_t packedSize = 0; +}; + +struct PackingOption { + std::string format; + uint8_t quality = 100; +}; + + +ImagePackerNapi::ImagePackerNapi() + :env_(nullptr), wrapper_(nullptr) +{} + +ImagePackerNapi::~ImagePackerNapi() +{ + if (wrapper_ != nullptr) { + napi_delete_reference(env_, wrapper_); + } +} + +static void CommonCallbackRoutine(napi_env env, ImagePackerAsyncContext* &asyncContext, const napi_value &valueParam) +{ + HiLog::Debug(LABEL, "CommonCallbackRoutine enter"); + napi_value result[2] = {0}; + napi_value retVal; + napi_value callback = nullptr; + + napi_get_undefined(env, &result[0]); + napi_get_undefined(env, &result[1]); + + if (asyncContext->status == SUCCESS) { + result[1] = valueParam; + } + + if (asyncContext->deferred) { + if (asyncContext->status == SUCCESS) { + napi_resolve_deferred(env, asyncContext->deferred, result[1]); + } else { + napi_reject_deferred(env, asyncContext->deferred, result[0]); + } + } else { + napi_get_reference_value(env, asyncContext->callbackRef, &callback); + napi_call_function(env, nullptr, callback, PARAM2, result, &retVal); + napi_delete_reference(env, asyncContext->callbackRef); + } + + napi_delete_async_work(env, asyncContext->work); + + delete asyncContext; + asyncContext = nullptr; + HiLog::Debug(LABEL, "CommonCallbackRoutine exit"); +} + +STATIC_EXEC_FUNC(Packing) +{ + HiLog::Debug(LABEL, "PackingExec enter"); + uint64_t bufferSize = 2 * 1024 * 1024; + int64_t packedSize = 0; + auto context = static_cast(data); + HiLog::Debug(LABEL, "image packer get supported format"); + std::set formats; + uint32_t ret = context->rImagePacker->GetSupportedFormats(formats); + if (ret != SUCCESS) { + HiLog::Error(LABEL, "image packer get supported format failed, ret=%{public}u.", ret); + } + + uint32_t errorCode = 0; + HiLog::Debug(LABEL, "image packer GetSourceInfo format"); + SourceInfo sourceInfo = context->rImageSource->GetSourceInfo(errorCode); + HiLog::Debug(LABEL, "image packer GetSourceInfo format, ret=%{public}u.", errorCode); + + context->resultBuffer = malloc(bufferSize); + if (context->resultBuffer == nullptr) { + HiLog::Error(LABEL, "PackingExec failed, malloc buffer failed"); + + context->status = ERROR; + } else { + context->rImagePacker->StartPacking(static_cast(context->resultBuffer), + bufferSize, context->packOption); + context->rImagePacker->AddImage(*(context->rImageSource)); + context->rImagePacker->FinalizePacking(packedSize); + HiLog::Debug(LABEL, "packedSize=%{public}lld.", static_cast(packedSize)); + + if (packedSize > 0) { + context->packedSize = packedSize; + context->status = SUCCESS; + } else { + context->status = ERROR; + } + } + HiLog::Debug(LABEL, "PackingExec exit"); +} + +STATIC_COMPLETE_FUNC(Packing) +{ + HiLog::Debug(LABEL, "PackingComplete enter"); + napi_value result = nullptr; + napi_get_undefined(env, &result); + auto context = static_cast(data); + status = napi_create_arraybuffer(env, context->packedSize, &(context->resultBuffer), &result); + if (!IMG_IS_OK(status)) { + context->status = ERROR; + HiLog::Error(LABEL, "napi_create_arraybuffer failed!"); + napi_get_undefined(env, &result); + } else { + context->status = SUCCESS; + } + HiLog::Debug(LABEL, "PackingComplete exit"); + CommonCallbackRoutine(env, context, result); +} + +napi_value ImagePackerNapi::Init(napi_env env, napi_value exports) +{ + napi_property_descriptor props[] = { + DECLARE_NAPI_FUNCTION("packing", Packing), + DECLARE_NAPI_FUNCTION("release", Release), + }; + napi_property_descriptor static_prop[] = { + DECLARE_NAPI_STATIC_FUNCTION("createImagePacker", CreateImagePacker), + }; + + napi_value constructor = nullptr; + + IMG_NAPI_CHECK_RET_D(IMG_IS_OK( + napi_define_class(env, CLASS_NAME_IMAGEPACKER.c_str(), NAPI_AUTO_LENGTH, Constructor, + nullptr, IMG_ARRAY_SIZE(props), props, &constructor)), nullptr, + HiLog::Error(LABEL, "define class fail") + ); + + IMG_NAPI_CHECK_RET_D(IMG_IS_OK( + napi_create_reference(env, constructor, 1, &sConstructor_)), + nullptr, + HiLog::Error(LABEL, "create reference fail") + ); + + IMG_NAPI_CHECK_RET_D(IMG_IS_OK( + napi_set_named_property(env, exports, CLASS_NAME_IMAGEPACKER.c_str(), constructor)), + nullptr, + HiLog::Error(LABEL, "set named property fail") + ); + IMG_NAPI_CHECK_RET_D(IMG_IS_OK( + napi_define_properties(env, exports, IMG_ARRAY_SIZE(static_prop), static_prop)), + nullptr, + HiLog::Error(LABEL, "define properties fail") + ); + + HiLog::Debug(LABEL, "Init success"); + return exports; +} + +napi_value ImagePackerNapi::Constructor(napi_env env, napi_callback_info info) +{ + napi_value undefineVar = nullptr; + napi_get_undefined(env, &undefineVar); + + napi_status status; + napi_value thisVar = nullptr; + + HiLog::Debug(LABEL, "Constructor in"); + status = napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + if (status == napi_ok && thisVar != nullptr) { + std::unique_ptr pImgPackerNapi = std::make_unique(); + if (pImgPackerNapi != nullptr) { + pImgPackerNapi->env_ = env; + pImgPackerNapi->nativeImgPck = sImgPck_; + status = napi_wrap(env, thisVar, reinterpret_cast(pImgPackerNapi.get()), + ImagePackerNapi::Destructor, nullptr, &(pImgPackerNapi->wrapper_)); + if (status == napi_ok) { + pImgPackerNapi.release(); + return thisVar; + } else { + HiLog::Error(LABEL, "Failure wrapping js to native napi"); + } + } + } + + return undefineVar; +} + +napi_value ImagePackerNapi::CreateImagePacker(napi_env env, napi_callback_info info) +{ + napi_value constructor = nullptr; + napi_value result = nullptr; + napi_status status; + + HiLog::Debug(LABEL, "CreateImagePacker IN"); + std::shared_ptr imagePacker = std::make_shared(); + status = napi_get_reference_value(env, sConstructor_, &constructor); + if (IMG_IS_OK(status)) { + sImgPck_ = imagePacker; + status = napi_new_instance(env, constructor, 0, nullptr, &result); + if (status == napi_ok) { + return result; + } else { + HiLog::Error(LABEL, "New instance could not be obtained"); + } + } + return result; +} + +void ImagePackerNapi::Destructor(napi_env env, void *nativeObject, void *finalize) +{ + ImagePackerNapi *pImagePackerNapi = reinterpret_cast(nativeObject); + + if (IMG_NOT_NULL(pImagePackerNapi)) { + pImagePackerNapi->~ImagePackerNapi(); + } +} + +static bool parsePackOptions(napi_env env, napi_value root, PackOption* opts) +{ + char buffer[SIZE]; + napi_value property = nullptr; + bool present = false; + size_t res; + uint32_t len = 0; + napi_value stringItem = nullptr; + int32_t quality = 0; + HiLog::Debug(LABEL, "GetPackingOptionsParam IN"); + + napi_has_named_property(env, root, "format", &present); + if (present && napi_get_named_property(env, root, "format", &property) == napi_ok) { + HiLog::Debug(LABEL, "GetPackingOptionsParam IN 1"); + napi_get_array_length(env, property, &len); + for (size_t i = 0; i < len; i++) { + napi_get_element(env, property, i, &stringItem); + napi_get_value_string_utf8(env, stringItem, buffer, SIZE, &res); + opts->format = std::string(buffer); + HiLog::Debug(LABEL, "format is %{public}s.", opts->format.c_str()); + if (memset_s(buffer, SIZE, 0, sizeof(buffer)) != EOK) { + HiLog::Error(LABEL, "memset buffer failed."); + free(buffer); + } + } + } + present = false; + napi_has_named_property(env, root, "quality", &present); + if (present) { + if (napi_get_named_property(env, root, "quality", &property) != napi_ok) { + HiLog::Error(LABEL, "Could not get the quality argument!"); + } else { + napi_get_value_int32(env, property, &quality); + opts->quality = quality; + HiLog::Debug(LABEL, "quality is %{public}u.", quality); + } + } + return true; +} + +napi_value ImagePackerNapi::Packing(napi_env env, napi_callback_info info) +{ + napi_status status; + napi_value result = nullptr; + size_t argc = ARGS_THREE; + napi_value argv[ARGS_THREE] = {0}; + napi_value thisVar = nullptr; + int32_t refCount = 1; + + std::shared_ptr imagesourceObj = nullptr; + std::unique_ptr pixelMap = nullptr; + HiLog::Debug(LABEL, "Packing IN"); + + IMG_JS_ARGS(env, info, status, argc, argv, thisVar); + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), nullptr, HiLog::Error(LABEL, "fail to napi_get_cb_info")); + + std::unique_ptr asyncContext = std::make_unique(); + status = napi_unwrap(env, thisVar, reinterpret_cast(&asyncContext->constructor_)); + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->constructor_), + nullptr, HiLog::Error(LABEL, "fail to unwrap constructor_")); + + asyncContext->rImagePacker = std::move(asyncContext->constructor_->nativeImgPck); + for (size_t i = PARAM0; i < argc; i++) { + napi_valuetype argvType = ImageNapiUtils::getType(env, argv[i]); + if (i == PARAM0 && argvType == napi_object) { + std::shared_ptr imageSourceNapi = std::make_unique(); + status = napi_unwrap(env, argv[i], reinterpret_cast(&imageSourceNapi)); + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, imageSourceNapi), nullptr, + HiLog::Error(LABEL, "fail to unwrap ImageSourceNapi")); + asyncContext->rImageSource = imageSourceNapi->nativeImgSrc; + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(asyncContext->rImageSource == nullptr), nullptr, + HiLog::Error(LABEL, "fail to napi_get rImageSource")); + } else if (i == PARAM1 && ImageNapiUtils::getType(env, argv[i]) == napi_object) { + IMG_NAPI_CHECK_RET_D(parsePackOptions(env, argv[i], &(asyncContext->packOption)), + nullptr, HiLog::Error(LABEL, "PackOptions mismatch")); + } else if (i == PARAM2 && ImageNapiUtils::getType(env, argv[i]) == napi_function) { + napi_create_reference(env, argv[i], refCount, &asyncContext->callbackRef); + break; + } + } + + if (asyncContext->callbackRef == nullptr) { + napi_create_promise(env, &(asyncContext->deferred), &result); + } else { + napi_get_undefined(env, &result); + } + + IMG_CREATE_CREATE_ASYNC_WORK(env, status, "Packing", + PackingExec, PackingComplete, asyncContext, asyncContext->work); + + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), + nullptr, HiLog::Error(LABEL, "fail to create async work")); + return result; +} + +napi_value ImagePackerNapi::Release(napi_env env, napi_callback_info info) +{ + HiLog::Debug(LABEL, "Release enter"); + napi_value result = nullptr; + napi_get_undefined(env, &result); + + napi_status status; + napi_value thisVar = nullptr; + size_t argCount = 0; + + IMG_JS_ARGS(env, info, status, argCount, nullptr, thisVar); + + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), result, HiLog::Error(LABEL, "fail to napi_get_cb_info")); + + std::unique_ptr imagePackerNapi = std::make_unique(); + status = napi_unwrap(env, thisVar, reinterpret_cast(&imagePackerNapi)); + + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, imagePackerNapi), result, HiLog::Error(LABEL, "fail to unwrap context")); + + imagePackerNapi->~ImagePackerNapi(); + HiLog::Debug(LABEL, "Release exit"); + return result; +} +} // namespace Media +} // namespace OHOS diff --git a/frameworks/kits/js/common/image_source_napi.cpp b/frameworks/kits/js/common/image_source_napi.cpp index bb103556917d0dab1e1da51c387893b89ab73615..84f62ddb449feeae81c4557057d9d38bba2b6c61 100644 --- a/frameworks/kits/js/common/image_source_napi.cpp +++ b/frameworks/kits/js/common/image_source_napi.cpp @@ -13,19 +13,28 @@ * limitations under the License. */ -#include "hilog/log.h" #include "image_source_napi.h" +#include +#include "hilog/log.h" +#include "image_napi_utils.h" #include "media_errors.h" using OHOS::HiviewDFX::HiLog; namespace { constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, LOG_DOMAIN, "ImageSourceNapi"}; + constexpr uint32_t NUM_0 = 0; + constexpr uint32_t NUM_1 = 1; + constexpr uint32_t NUM_2 = 2; + constexpr uint32_t NUM_3 = 3; + constexpr uint32_t NUM_4 = 4; + constexpr uint32_t NUM_5 = 5; } namespace OHOS { namespace Media { napi_ref ImageSourceNapi::sConstructor_ = nullptr; -static const std::string CLASS_NAME = "PixelMap"; +std::shared_ptr ImageSourceNapi::sImgSrc_ = nullptr; +static const std::string CLASS_NAME = "ImageSource"; struct ImageSourceAsyncContext { napi_env env; @@ -33,19 +42,100 @@ struct ImageSourceAsyncContext { napi_deferred deferred; napi_ref callbackRef = nullptr; ImageSourceNapi *constructor_; + uint32_t status; + std::string pathName; + int fdIndex; + void* sourceBuffer; + size_t sourceBufferSize; + std::string keyStr; + std::string valueStr; + int32_t valueInt; + int32_t deufltValueInt; + void *updataBuffer; + size_t updataBufferSize; + uint32_t updataBufferOffset = 0; + uint32_t updataLength = 0; + bool isCompleted = false; + bool isSuccess = false; + size_t pathNameLength; + SourceOptions opts; + uint32_t index; + ImageInfo imageInfo; + DecodeOptions decodeOpts; + std::shared_ptr rImageSource; + std::shared_ptr rPixelMap; }; +static std::string GetStringArgument(napi_env env, napi_value value) +{ + std::string strValue = ""; + size_t bufLength = 0; + napi_status status = napi_get_value_string_utf8(env, value, nullptr, NUM_0, &bufLength); + if (status == napi_ok && bufLength > NUM_0 && bufLength < PATH_MAX) { + char *buffer = (char *)malloc((bufLength + NUM_1) * sizeof(char)); + if (buffer == nullptr) { + HiLog::Error(LABEL, "No memory"); + return strValue; + } + + status = napi_get_value_string_utf8(env, value, buffer, bufLength + NUM_1, &bufLength); + if (status == napi_ok) { + HiLog::Debug(LABEL, "Get Success"); + strValue = buffer; + } + free(buffer); + buffer = nullptr; + } + return strValue; +} + +static void ImageSourceCallbackRoutine(napi_env env, ImageSourceAsyncContext* &context, const napi_value &valueParam) +{ + napi_value result[NUM_2] = {0}; + napi_value retVal; + napi_value callback = nullptr; + + napi_get_undefined(env, &result[NUM_0]); + napi_get_undefined(env, &result[NUM_1]); + + if (context->status == SUCCESS) { + result[NUM_1] = valueParam; + } + + if (context->deferred) { + if (context->status == SUCCESS) { + napi_resolve_deferred(env, context->deferred, result[NUM_1]); + } else { + napi_reject_deferred(env, context->deferred, result[0]); + } + } else { + HiLog::Debug(LABEL, "call callback function"); + napi_get_reference_value(env, context->callbackRef, &callback); + napi_call_function(env, nullptr, callback, NUM_2, result, &retVal); + napi_delete_reference(env, context->callbackRef); + } + + napi_delete_async_work(env, context->work); + + delete context; + context = nullptr; +} + ImageSourceNapi::ImageSourceNapi() + :env_(nullptr), wrapper_(nullptr) { } ImageSourceNapi::~ImageSourceNapi() { - if (wrapper_ != nullptr) - { + if (nativeImgSrc != nullptr) { + nativeImgSrc = nullptr; + } + if (wrapper_ != nullptr) { napi_delete_reference(env_, wrapper_); } + isRelease = true; } napi_value ImageSourceNapi::Init(napi_env env, napi_value exports) @@ -67,31 +157,27 @@ napi_value ImageSourceNapi::Init(napi_env env, napi_value exports) napi_value constructor = nullptr; napi_status status = napi_define_class(env, CLASS_NAME.c_str(), NAPI_AUTO_LENGTH, Constructor, nullptr, - sizeof(properties) / sizeof(properties[0]), properties, &constructor); + sizeof(properties) / sizeof(properties[NUM_0]), properties, &constructor); - if (status != napi_ok) - { + if (status != napi_ok) { HiLog::Error(LABEL, "define class fail"); return nullptr; } - status = napi_create_reference(env, constructor, 1, &sConstructor_); - if (status != napi_ok) - { + status = napi_create_reference(env, constructor, NUM_1, &sConstructor_); + if (status != napi_ok) { HiLog::Error(LABEL, "create reference fail"); return nullptr; } status = napi_set_named_property(env, exports, CLASS_NAME.c_str(), constructor); - if (status != napi_ok) - { + if (status != napi_ok) { HiLog::Error(LABEL, "set named property fail"); return nullptr; } - - status = napi_define_properties(env, exports, sizeof(static_prop) / sizeof(static_prop[0]), static_prop); - if (status != napi_ok) - { + + status = napi_define_properties(env, exports, sizeof(static_prop) / sizeof(static_prop[NUM_0]), static_prop); + if (status != napi_ok) { HiLog::Error(LABEL, "define properties fail"); return nullptr; } @@ -109,23 +195,18 @@ napi_value ImageSourceNapi::Constructor(napi_env env, napi_callback_info info) status = napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); - if (status == napi_ok && thisVar != nullptr) - { + if (status == napi_ok && thisVar != nullptr) { std::unique_ptr pImgSrcNapi = std::make_unique(); - if (pImgSrcNapi != nullptr) - { + if (pImgSrcNapi != nullptr) { pImgSrcNapi->env_ = env; pImgSrcNapi->nativeImgSrc = sImgSrc_; - status = napi_wrap(env, thisVar, reinterpret_cast(pImgSrcNapi.get()), + status = napi_wrap(env, thisVar, reinterpret_cast(pImgSrcNapi.get()), ImageSourceNapi::Destructor, nullptr, &(pImgSrcNapi->wrapper_)); - if (status == napi_ok) - { + if (status == napi_ok) { pImgSrcNapi.release(); return thisVar; - } - else - { + } else { HiLog::Error(LABEL, "Failure wrapping js to native napi"); } } @@ -137,134 +218,738 @@ napi_value ImageSourceNapi::Constructor(napi_env env, napi_callback_info info) void ImageSourceNapi::Destructor(napi_env env, void *nativeObject, void *finalize) { ImageSourceNapi *pImgSrcNapi = reinterpret_cast(nativeObject); - if (pImgSrcNapi != nullptr) - { + if (pImgSrcNapi != nullptr) { pImgSrcNapi->~ImageSourceNapi(); } } -static void GetSupportedFormatsExecute(napi_env env, void *data) +napi_value ImageSourceNapi::GetSupportedFormats(napi_env env, napi_callback_info info) { + napi_value result = nullptr; + napi_get_undefined(env, &result); + napi_status status; + napi_value thisVar = nullptr; + size_t argCount = 0; + HiLog::Debug(LABEL, "GetSupportedFormats IN"); + + IMG_JS_ARGS(env, info, status, argCount, nullptr, thisVar); + + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), result, HiLog::Error(LABEL, "fail to napi_get_cb_info")); + + std::unique_ptr asyncContext = std::make_unique(); + status = napi_unwrap(env, thisVar, reinterpret_cast(&asyncContext->constructor_)); + + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->constructor_), + nullptr, HiLog::Error(LABEL, "fail to unwrap context")); + std::set formats; + uint32_t ret = asyncContext->constructor_->nativeImgSrc->GetSupportedFormats(formats); + + IMG_NAPI_CHECK_RET_D((ret == SUCCESS), + nullptr, HiLog::Error(LABEL, "fail to get supported formats")); + + napi_create_array(env, &result); + size_t i = 0; + for (const std::string& formatStr: formats) { + napi_value format = nullptr; + napi_create_string_latin1(env, formatStr.c_str(), formatStr.length(), &format); + napi_set_element(env, result, i, format); + i++; + } + return result; } -static void GetSupportedFormatsComplete(napi_env env, napi_status status, void *data) +STATIC_COMPLETE_FUNC(GetImageInfo) { + HiLog::Debug(LABEL, "[ImageSource]GetImageInfoComplete IN"); + napi_value result = nullptr; + napi_create_object(env, &result); + + auto context = static_cast(data); + + napi_value size = nullptr; + napi_create_object(env, &size); + + napi_value sizeWith = nullptr; + napi_create_int32(env, context->imageInfo.size.width, &sizeWith); + napi_set_named_property(env, size, "width", sizeWith); + + napi_value sizeHeight = nullptr; + napi_create_int32(env, context->imageInfo.size.height, &sizeHeight); + napi_set_named_property(env, size, "height", sizeHeight); + napi_set_named_property(env, result, "size", size); + + napi_value pixelFormatValue = nullptr; + napi_create_int32(env, static_cast(context->imageInfo.pixelFormat), &pixelFormatValue); + napi_set_named_property(env, result, "pixelFormat", pixelFormatValue); + + napi_value colorSpaceValue = nullptr; + napi_create_int32(env, static_cast(context->imageInfo.colorSpace), &colorSpaceValue); + napi_set_named_property(env, result, "colorSpace", colorSpaceValue); + + napi_value alphaTypeValue = nullptr; + napi_create_int32(env, static_cast(context->imageInfo.alphaType), &alphaTypeValue); + napi_set_named_property(env, result, "alphaType", alphaTypeValue); + + if (!IMG_IS_OK(status)) { + context->status = ERROR; + HiLog::Error(LABEL, "napi_create_int32 failed!"); + napi_get_undefined(env, &result); + } else { + context->status = SUCCESS; + } + HiLog::Debug(LABEL, "[ImageSource]GetImageInfoComplete OUT"); + ImageSourceCallbackRoutine(env, context, result); } -napi_value ImageSourceNapi::GetSupportedFormats(napi_env env, napi_callback_info info) +static bool ParseSize(napi_env env, napi_value root, Size* size) { - return nullptr; + if (!GET_INT32_BY_NAME(root, "height", size->height)) { + return false; + } + + if (!GET_INT32_BY_NAME(root, "width", size->width)) { + return false; + } + + return true; } -napi_value ImageSourceNapi::CreateImageSource(napi_env env, napi_callback_info info) +static bool ParseRegion(napi_env env, napi_value root, Rect* region) +{ + napi_value tmpValue = nullptr; + + if (!GET_INT32_BY_NAME(root, "x", region->left)) { + return false; + } + + if (!GET_INT32_BY_NAME(root, "y", region->top)) { + return false; + } + + if (!GET_NODE_BY_NAME(root, "size", tmpValue)) { + return false; + } + + if (!GET_INT32_BY_NAME(tmpValue, "height", region->height)) { + return false; + } + + if (!GET_INT32_BY_NAME(tmpValue, "width", region->width)) { + return false; + } + + return true; +} + +static PixelFormat ParsePixlForamt(int32_t val) { + if (val <= static_cast(PixelFormat::CMYK)) { + return PixelFormat(val); + } - return nullptr; + return PixelFormat::UNKNOWN; } -napi_value ImageSourceNapi::CreateIncrementalSource(napi_env env, napi_callback_info info) +static bool ParseDecodeOptions(napi_env env, napi_value root, DecodeOptions* opts) +{ + uint32_t tmpNumber = 0; + napi_value tmpValue = nullptr; + + if (!GET_UINT32_BY_NAME(root, "sampleSize", opts->sampleSize)) { + HiLog::Debug(LABEL, "no sampleSize"); + } + + if (!GET_UINT32_BY_NAME(root, "rotateDegrees", opts->rotateNewDegrees)) { + HiLog::Debug(LABEL, "no rotateDegrees"); + } + + if (!GET_BOOL_BY_NAME(root, "editable", opts->editable)) { + HiLog::Debug(LABEL, "no editable"); + } + + if (!GET_NODE_BY_NAME(root, "desiredSize", tmpValue)) { + HiLog::Debug(LABEL, "no desiredSize"); + } else { + if (!ParseSize(env, tmpValue, &(opts->desiredSize))) { + HiLog::Debug(LABEL, "ParseSize error"); + } + } + + if (!GET_NODE_BY_NAME(root, "desiredRegion", tmpValue)) { + HiLog::Debug(LABEL, "no rotateDegrees"); + } else { + if (!ParseRegion(env, tmpValue, &(opts->desiredRegion))) { + HiLog::Debug(LABEL, "ParseRegion error"); + } + } + + tmpNumber = 0; + if (!GET_UINT32_BY_NAME(root, "desiredPixelFormat", tmpNumber)) { + HiLog::Debug(LABEL, "no rotateDegrees"); + } else { + opts->desiredPixelFormat = ParsePixlForamt(tmpNumber); + } + return true; +} + +napi_value ImageSourceNapi::CreateImageSource(napi_env env, napi_callback_info info) { - return nullptr; + napi_value result = nullptr; + napi_get_undefined(env, &result); + + napi_status status; + napi_value thisVar = nullptr; + napi_value argValue[NUM_2] = {0}; + size_t argCount = 2; + IMG_JS_ARGS(env, info, status, argCount, argValue, thisVar); + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), nullptr, HiLog::Error(LABEL, "fail to napi_get_cb_info")); + + std::unique_ptr asyncContext = std::make_unique(); + uint32_t errorCode = ERR_MEDIA_INVALID_VALUE; + SourceOptions opts; + std::unique_ptr imageSource = nullptr; + if (argCount == NUM_1 && ImageNapiUtils::getType(env, argValue[NUM_0]) == napi_string) { + size_t bufferSize = 0; + status = napi_get_value_string_utf8(env, argValue[NUM_0], nullptr, NUM_0, &bufferSize); + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status) && bufferSize > (size_t)0, nullptr, + HiLog::Error(LABEL, "fail to get bufferSize")); + + char* buffer = new char[bufferSize + NUM_1] { 0 }; + status = napi_get_value_string_utf8(env, argValue[NUM_0], buffer, + bufferSize + NUM_1, &(asyncContext->pathNameLength)); + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), nullptr, HiLog::Error(LABEL, "fail to get pathName")); + + asyncContext->pathName = buffer; + + HiLog::Debug(LABEL, "pathName is [%{public}s]", asyncContext->pathName.c_str()); + imageSource = ImageSource::CreateImageSource(asyncContext->pathName, opts, errorCode); + } else if (argCount == NUM_1 && ImageNapiUtils::getType(env, argValue[NUM_0]) == napi_number) { + napi_get_value_int32(env, argValue[NUM_0], &asyncContext->fdIndex); + HiLog::Debug(LABEL, "CreateImageSource fdIndex is [%{public}d]", asyncContext->fdIndex); + imageSource = ImageSource::CreateImageSource(asyncContext->fdIndex, opts, errorCode); + } else if (argCount == NUM_1) { + status = napi_get_arraybuffer_info(env, argValue[NUM_0], + &(asyncContext->sourceBuffer), &(asyncContext->sourceBufferSize)); + imageSource = ImageSource::CreateImageSource(static_cast(asyncContext->sourceBuffer), + asyncContext->sourceBufferSize, opts, errorCode); + } + + if (errorCode != SUCCESS || imageSource == nullptr) { + HiLog::Error(LABEL, "CreateImageSourceExec error"); + napi_get_undefined(env, &result); + return result; + } + napi_value constructor = nullptr; + status = napi_get_reference_value(env, sConstructor_, &constructor); + if (IMG_IS_OK(status)) { + sImgSrc_ = std::move(imageSource); + status = napi_new_instance(env, constructor, NUM_0, nullptr, &result); + } + if (!IMG_IS_OK(status)) { + HiLog::Error(LABEL, "New instance could not be obtained"); + napi_get_undefined(env, &result); + } + return result; } -static void GetImageInfoExecute(napi_env env, void *data) +napi_value ImageSourceNapi::CreateImageSourceComplete(napi_env env, napi_status status, void *data) { + napi_value constructor = nullptr; + napi_value result = nullptr; + + HiLog::Debug(LABEL, "CreateImageSourceComplete IN"); + auto context = static_cast(data); + status = napi_get_reference_value(env, sConstructor_, &constructor); + + if (IMG_IS_OK(status)) { + sImgSrc_ = context->rImageSource; + status = napi_new_instance(env, constructor, NUM_0, nullptr, &result); + } + + if (!IMG_IS_OK(status)) { + context->status = ERROR; + HiLog::Error(LABEL, "New instance could not be obtained"); + napi_get_undefined(env, &result); + } + return result; } -static void GetImageInfoComplete(napi_env env, napi_status status, void *data) +napi_value ImageSourceNapi::CreateIncrementalSource(napi_env env, napi_callback_info info) { + napi_value result = nullptr; + napi_get_undefined(env, &result); + napi_status status; + HiLog::Debug(LABEL, "CreateIncrementalSource IN"); + + uint32_t errorCode = 0; + IncrementalSourceOptions incOpts; + incOpts.incrementalMode = IncrementalMode::INCREMENTAL_DATA; + std::unique_ptr imageSource = ImageSource::CreateIncrementalImageSource(incOpts, errorCode); + HiLog::Debug(LABEL, "CreateIncrementalImageSource end"); + if (errorCode != SUCCESS || imageSource == nullptr) { + HiLog::Error(LABEL, "CreateIncrementalImageSource error"); + napi_get_undefined(env, &result); + return result; + } + napi_value constructor = nullptr; + status = napi_get_reference_value(env, sConstructor_, &constructor); + if (IMG_IS_OK(status)) { + sImgSrc_ = std::move(imageSource); + status = napi_new_instance(env, constructor, NUM_0, nullptr, &result); + } + if (!IMG_IS_OK(status)) { + HiLog::Error(LABEL, "New instance could not be obtained"); + napi_get_undefined(env, &result); + } + return result; } napi_value ImageSourceNapi::GetImageInfo(napi_env env, napi_callback_info info) { - return nullptr; + napi_value result = nullptr; + napi_get_undefined(env, &result); + int32_t refCount = 1; + napi_status status; + napi_value thisVar = nullptr; + napi_value argValue[NUM_2] = {0}; + size_t argCount = 2; + HiLog::Debug(LABEL, "GetImageInfo IN"); + IMG_JS_ARGS(env, info, status, argCount, argValue, thisVar); + HiLog::Debug(LABEL, "GetImageInfo argCount is [%{public}zu]", argCount); + + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), nullptr, HiLog::Error(LABEL, "fail to napi_get_cb_info")); + + std::unique_ptr asyncContext = std::make_unique(); + status = napi_unwrap(env, thisVar, reinterpret_cast(&asyncContext->constructor_)); + + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->constructor_), + nullptr, HiLog::Error(LABEL, "fail to unwrap context")); + + asyncContext->rImageSource = asyncContext->constructor_->nativeImgSrc; + + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->rImageSource), + nullptr, HiLog::Error(LABEL, "empty native pixelmap")); + HiLog::Debug(LABEL, "GetImageInfo argCount is [%{public}zu]", argCount); + if (argCount == NUM_1 && ImageNapiUtils::getType(env, argValue[NUM_0]) == napi_function) { + HiLog::Debug(LABEL, "GetImageInfo arg0 getType is [%{public}u]", ImageNapiUtils::getType(env, argValue[NUM_0])); + napi_create_reference(env, argValue[NUM_0], refCount, &asyncContext->callbackRef); + } else if (argCount == NUM_1 && ImageNapiUtils::getType(env, argValue[NUM_0]) == napi_number) { + napi_get_value_uint32(env, argValue[NUM_0], &asyncContext->index); + } else if (argCount == NUM_2 && ImageNapiUtils::getType(env, argValue[NUM_0]) == napi_number + && ImageNapiUtils::getType(env, argValue[NUM_1]) == napi_function) { + + HiLog::Debug(LABEL, "GetImageInfo arg0 getType is [%{public}u]", ImageNapiUtils::getType(env, argValue[NUM_0])); + HiLog::Debug(LABEL, "GetImageInfo arg1 getType is [%{public}u]", ImageNapiUtils::getType(env, argValue[NUM_1])); + napi_get_value_uint32(env, argValue[NUM_0], &asyncContext->index); + napi_create_reference(env, argValue[NUM_1], refCount, &asyncContext->callbackRef); + } + + if (asyncContext->callbackRef == nullptr) { + napi_create_promise(env, &(asyncContext->deferred), &result); + } else { + napi_get_undefined(env, &result); + } + + IMG_CREATE_CREATE_ASYNC_WORK(env, status, "GetImageInfo", + [](napi_env env, void *data) { + auto context = static_cast(data); + context->rImageSource->GetImageInfo(NUM_0, context->imageInfo); + context->status = SUCCESS; + + }, GetImageInfoComplete, asyncContext, asyncContext->work); + + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), + nullptr, HiLog::Error(LABEL, "fail to create async work")); + return result; } static void CreatePixelMapExecute(napi_env env, void *data) { - + HiLog::Debug(LABEL, "CreatePixelMapExecute IN"); + uint32_t errorCode = 0; + auto context = static_cast(data); + if (context == nullptr) + HiLog::Error(LABEL, "empty context"); + + if (context->rImageSource == nullptr) + HiLog::Error(LABEL, "empty context rImageSource"); + + context->rPixelMap = context->rImageSource->CreatePixelMap(context->decodeOpts, errorCode); + + if (context->rPixelMap == nullptr) + HiLog::Error(LABEL, "empty context rPixelMap"); + HiLog::Error(LABEL, "CreatePixelMap out"); + if (IMG_NOT_NULL(context->rPixelMap)) { + context->status = SUCCESS; + } else { + context->status = ERROR; + } + HiLog::Debug(LABEL, "CreatePixelMapExecute OUT"); } static void CreatePixelMapComplete(napi_env env, napi_status status, void *data) { + HiLog::Debug(LABEL, "CreatePixelMapComplete IN"); + napi_value result = nullptr; + napi_create_object(env, &result); + + auto context = static_cast(data); + result = PixelMapNapi::CreatePixelMap(env, context->rPixelMap); + HiLog::Debug(LABEL, "CreatePixelMapComplete OUT"); + ImageSourceCallbackRoutine(env, context, result); } napi_value ImageSourceNapi::CreatePixelMap(napi_env env, napi_callback_info info) { - return nullptr; + napi_value result = nullptr; + napi_get_undefined(env, &result); -} + int32_t refCount = 1; + napi_status status; + napi_value thisVar = nullptr; + napi_value argValue[NUM_3] = {0}; + size_t argCount = 3; + IMG_JS_ARGS(env, info, status, argCount, argValue, thisVar); + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, thisVar), nullptr, HiLog::Error(LABEL, "fail to get thisVar")); + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), nullptr, HiLog::Error(LABEL, "fail to napi_get_cb_info")); + + std::unique_ptr asyncContext = std::make_unique(); + + std::shared_ptr imageSourceNapi = std::make_unique(); + status = napi_unwrap(env, thisVar, reinterpret_cast(&imageSourceNapi)); + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, imageSourceNapi), + nullptr, HiLog::Error(LABEL, "fail to unwrap context")); + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, imageSourceNapi->nativeImgSrc), + nullptr, HiLog::Error(LABEL, "fail to unwrap nativeImgSrc")); + + asyncContext->rImageSource = imageSourceNapi->nativeImgSrc; + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->rImageSource), + nullptr, HiLog::Error(LABEL, "empty native rImageSource")); + + if (argCount == NUM_2) { + if (ImageNapiUtils::getType(env, argValue[NUM_1]) == napi_function) + napi_create_reference(env, argValue[NUM_1], refCount, &asyncContext->callbackRef); + if (ImageNapiUtils::getType(env, argValue[NUM_0]) == napi_object) { + IMG_NAPI_CHECK_RET_D(ParseDecodeOptions(env, argValue[NUM_0], &(asyncContext->decodeOpts)), + nullptr, HiLog::Error(LABEL, "DecodeOptions mismatch")); + } + } else if (argCount == NUM_3) { + if (ImageNapiUtils::getType(env, argValue[NUM_0]) == napi_number) + napi_get_value_uint32(env, argValue[NUM_0], &asyncContext->index); -static void GetImagePropertyIntExecute(napi_env env, void *data) -{ + if (ImageNapiUtils::getType(env, argValue[NUM_1]) == napi_object) { + IMG_NAPI_CHECK_RET_D(ParseDecodeOptions(env, argValue[NUM_1], &(asyncContext->decodeOpts)), + nullptr, HiLog::Error(LABEL, "DecodeOptions mismatch")); + } + + if (ImageNapiUtils::getType(env, argValue[NUM_2]) == napi_function) + napi_create_reference(env, argValue[NUM_2], refCount, &asyncContext->callbackRef); + + } else { + HiLog::Error(LABEL, "argCount missmatch"); + return result; + } + + if (asyncContext->callbackRef == nullptr) { + napi_create_promise(env, &(asyncContext->deferred), &result); + } else { + napi_get_undefined(env, &result); + } + + IMG_CREATE_CREATE_ASYNC_WORK(env, status, "CreatePixelMap", CreatePixelMapExecute, + CreatePixelMapComplete, asyncContext, asyncContext->work); + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), + nullptr, HiLog::Error(LABEL, "fail to create async work")); + return result; } static void GetImagePropertyIntComplete(napi_env env, napi_status status, void *data) { - + HiLog::Debug(LABEL, "GetImagePropertyIntComplete IN"); + napi_value result = nullptr; + napi_get_undefined(env, &result); + + auto context = static_cast(data); + napi_create_int32(env, context->valueInt, &result); + HiLog::Debug(LABEL, "GetImagePropertyIntComplete OUT"); + ImageSourceCallbackRoutine(env, context, result); } napi_value ImageSourceNapi::GetImagePropertyInt(napi_env env, napi_callback_info info) { - return nullptr; + napi_value result = nullptr; + napi_get_undefined(env, &result); -} + int32_t refCount = 1; + napi_status status; + napi_value thisVar = nullptr; + napi_value argValue[NUM_4] = {0}; + size_t argCount = 4; + IMG_JS_ARGS(env, info, status, argCount, argValue, thisVar); + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), nullptr, HiLog::Error(LABEL, "fail to napi_get_cb_info")); -static void GetImagePropertyStringExecute(napi_env env, void *data) -{ + std::unique_ptr asyncContext = std::make_unique(); + status = napi_unwrap(env, thisVar, reinterpret_cast(&asyncContext->constructor_)); + + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->constructor_), + nullptr, HiLog::Error(LABEL, "fail to unwrap context")); + + asyncContext->rImageSource = asyncContext->constructor_->nativeImgSrc; + + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->rImageSource), + nullptr, HiLog::Error(LABEL, "empty native rImageSource")); + if (argCount > NUM_0 && ImageNapiUtils::getType(env, argValue[NUM_0]) == napi_number) { + napi_get_value_uint32(env, argValue[NUM_0], &asyncContext->index); + HiLog::Debug(LABEL, "asyncContext->index is [%{public}u]", asyncContext->index); + } + + if (argCount > NUM_2 && ImageNapiUtils::getType(env, argValue[NUM_1]) == napi_string) { + asyncContext->keyStr = GetStringArgument(env, argValue[NUM_1]); + HiLog::Debug(LABEL, "asyncContext->index is [%{public}s]", asyncContext->keyStr.c_str()); + } + if (argCount > NUM_3 && ImageNapiUtils::getType(env, argValue[NUM_2]) == napi_number) { + napi_get_value_int32(env, argValue[NUM_2], &asyncContext->deufltValueInt); + HiLog::Debug(LABEL, "asyncContext->deufltValueInt is [%{public}u]", asyncContext->deufltValueInt); + } + + if (argCount == NUM_4 && ImageNapiUtils::getType(env, argValue[NUM_3]) == napi_function) { + napi_create_reference(env, argValue[NUM_1], refCount, &asyncContext->callbackRef); + } + + if (asyncContext->callbackRef == nullptr) { + napi_create_promise(env, &(asyncContext->deferred), &result); + } else { + napi_get_undefined(env, &result); + } + + IMG_CREATE_CREATE_ASYNC_WORK(env, status, "GetImagePropertyInt", + [](napi_env env, void *data) { + auto context = static_cast(data); + uint32_t errorCode = context->rImageSource->GetImagePropertyInt(context->index, context->keyStr, + context->valueInt); + if (errorCode != SUCCESS) { + context->valueInt = context->deufltValueInt; + } + context->status = SUCCESS; + + }, GetImagePropertyIntComplete, asyncContext, asyncContext->work); + + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), + nullptr, HiLog::Error(LABEL, "fail to create async work")); + return result; } static void GetImagePropertyStringComplete(napi_env env, napi_status status, void *data) { + HiLog::Debug(LABEL, "GetImagePropertyStringComplete IN"); + napi_value result = nullptr; + napi_create_object(env, &result); + auto context = static_cast(data); + + napi_create_string_utf8(env, context->valueStr.c_str(), context->valueStr.length(), &result); + HiLog::Debug(LABEL, "GetImagePropertyStringComplete OUT"); + ImageSourceCallbackRoutine(env, context, result); } napi_value ImageSourceNapi::GetImagePropertyString(napi_env env, napi_callback_info info) { - return nullptr; + napi_value result = nullptr; + napi_get_undefined(env, &result); + + int32_t refCount = 1; + napi_status status; + napi_value thisVar = nullptr; + napi_value argValue[NUM_2] = {0}; + size_t argCount = 2; + HiLog::Debug(LABEL, "GetImagePropertyString IN"); + IMG_JS_ARGS(env, info, status, argCount, argValue, thisVar); + HiLog::Debug(LABEL, "GetImagePropertyString argCount is [%{public}zu]", argCount); + + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), nullptr, HiLog::Error(LABEL, "fail to napi_get_cb_info")); + + std::unique_ptr asyncContext = std::make_unique(); + status = napi_unwrap(env, thisVar, reinterpret_cast(&asyncContext->constructor_)); + + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->constructor_), + nullptr, HiLog::Error(LABEL, "fail to unwrap context")); + asyncContext->rImageSource = asyncContext->constructor_->nativeImgSrc; + + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->rImageSource), + nullptr, HiLog::Error(LABEL, "empty native rImageSource")); + + if (argCount > NUM_0 && ImageNapiUtils::getType(env, argValue[NUM_0]) == napi_string) { + asyncContext->keyStr = GetStringArgument(env, argValue[NUM_0]); + } + + if (argCount == NUM_2 && ImageNapiUtils::getType(env, argValue[NUM_1]) == napi_function) { + napi_create_reference(env, argValue[NUM_1], refCount, &asyncContext->callbackRef); + } + + if (asyncContext->callbackRef == nullptr) { + napi_create_promise(env, &(asyncContext->deferred), &result); + } else { + napi_get_undefined(env, &result); + } + + IMG_CREATE_CREATE_ASYNC_WORK(env, status, "GetImagePropertyString", + [](napi_env env, void *data) + { + auto context = static_cast(data); + context->rImageSource->GetImagePropertyString(NUM_0, context->keyStr, context->valueStr); + context->status = SUCCESS; + + }, GetImagePropertyStringComplete, asyncContext, asyncContext->work); + + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), + nullptr, HiLog::Error(LABEL, "fail to create async work")); + return result; } static void UpdateDataExecute(napi_env env, void *data) { - + auto context = static_cast(data); + context->isSuccess = context->rImageSource->UpdateData(static_cast(context->updataBuffer), + context->updataBufferSize, context->isCompleted); } static void UpdateDataComplete(napi_env env, napi_status status, void *data) { + HiLog::Debug(LABEL, "UpdateDataComplete IN"); + napi_value result = nullptr; + napi_create_object(env, &result); + auto context = static_cast(data); + + napi_get_boolean(env, context->isSuccess, &result); + HiLog::Debug(LABEL, "UpdateDataComplete OUT"); + ImageSourceCallbackRoutine(env, context, result); } napi_value ImageSourceNapi::UpdateData(napi_env env, napi_callback_info info) { - return nullptr; + napi_value result = nullptr; + napi_get_undefined(env, &result); -} + int32_t refCount = 1; + napi_status status; + napi_value thisVar = nullptr; + napi_value argValue[NUM_5] = {0}; + size_t argCount = 5; + HiLog::Debug(LABEL, "UpdateData IN"); + IMG_JS_ARGS(env, info, status, argCount, argValue, thisVar); + HiLog::Debug(LABEL, "UpdateData argCount is [%{public}zu]", argCount); -static void ReleaseExecute(napi_env env, void *data) -{ + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), nullptr, HiLog::Error(LABEL, "fail to napi_get_cb_info")); + + std::unique_ptr asyncContext = std::make_unique(); + status = napi_unwrap(env, thisVar, reinterpret_cast(&asyncContext->constructor_)); + + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->constructor_), + nullptr, HiLog::Error(LABEL, "fail to unwrap context")); + + asyncContext->rImageSource = asyncContext->constructor_->nativeImgSrc; + + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->rImageSource), + nullptr, HiLog::Error(LABEL, "empty native rImageSource")); + if (argCount > NUM_0 && ImageNapiUtils::getType(env, argValue[NUM_0]) == napi_string) { + size_t bufferSize = static_cast(asyncContext->updataBufferSize); + status = napi_get_arraybuffer_info(env, argValue[NUM_0], + &(asyncContext->updataBuffer), &bufferSize); + } + + if (argCount >= NUM_2 && ImageNapiUtils::getType(env, argValue[NUM_1]) == napi_boolean) { + status = napi_get_value_bool(env, argValue[NUM_1], &(asyncContext->isCompleted)); + } + + if (argCount >= NUM_3 && ImageNapiUtils::getType(env, argValue[NUM_2]) == napi_number) { + status = napi_get_value_uint32(env, argValue[NUM_2], &(asyncContext->updataBufferOffset)); + HiLog::Debug(LABEL, "asyncContext->updataBufferOffset is [%{public}u]", asyncContext->updataBufferOffset); + } + + if (argCount >= NUM_4 && ImageNapiUtils::getType(env, argValue[NUM_3]) == napi_number) { + status = napi_get_value_uint32(env, argValue[NUM_3], &(asyncContext->updataLength)); + HiLog::Debug(LABEL, "asyncContext->updataLength is [%{public}u]", asyncContext->updataLength); + } + + if (argCount == NUM_5 && ImageNapiUtils::getType(env, argValue[NUM_4]) == napi_function) { + napi_create_reference(env, argValue[NUM_4], refCount, &asyncContext->callbackRef); + } + + if (argCount == NUM_3 && ImageNapiUtils::getType(env, argValue[NUM_2]) == napi_function) { + napi_create_reference(env, argValue[NUM_2], refCount, &asyncContext->callbackRef); + } + + if (asyncContext->callbackRef == nullptr) { + napi_create_promise(env, &(asyncContext->deferred), &result); + } else { + napi_get_undefined(env, &result); + } + + IMG_CREATE_CREATE_ASYNC_WORK(env, status, "UpdateData", + UpdateDataExecute, UpdateDataComplete, asyncContext, asyncContext->work); + + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), + nullptr, HiLog::Error(LABEL, "fail to create async work")); + return result; } static void ReleaseComplete(napi_env env, napi_status status, void *data) { - + HiLog::Debug(LABEL, "ReleaseComplete IN"); + napi_value result = nullptr; + napi_get_undefined(env, &result); + + auto context = static_cast(data); + context->constructor_->~ImageSourceNapi(); + HiLog::Debug(LABEL, "ReleaseComplete OUT"); + ImageSourceCallbackRoutine(env, context, result); } napi_value ImageSourceNapi::Release(napi_env env, napi_callback_info info) { - return nullptr; + HiLog::Debug(LABEL, "Release enter"); + napi_value result = nullptr; + napi_get_undefined(env, &result); -} + int32_t refCount = 1; + napi_status status; + napi_value thisVar = nullptr; + napi_value argValue[NUM_1] = {0}; + size_t argCount = 1; + IMG_JS_ARGS(env, info, status, argCount, argValue, thisVar); + HiLog::Debug(LABEL, "Release argCount is [%{public}zu]", argCount); + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), result, HiLog::Error(LABEL, "fail to napi_get_cb_info")); + std::unique_ptr asyncContext = std::make_unique(); + status = napi_unwrap(env, thisVar, reinterpret_cast(&asyncContext->constructor_)); + + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->constructor_), result, + HiLog::Error(LABEL, "fail to unwrap context")); + HiLog::Debug(LABEL, "Release argCount is [%{public}zu]", argCount); + if (argCount == 1 && ImageNapiUtils::getType(env, argValue[NUM_0]) == napi_function) { + napi_create_reference(env, argValue[NUM_0], refCount, &asyncContext->callbackRef); + } + + if (asyncContext->callbackRef == nullptr) { + napi_create_promise(env, &(asyncContext->deferred), &result); + } + + IMG_CREATE_CREATE_ASYNC_WORK(env, status, "Release", + [](napi_env env, void *data) {}, ReleaseComplete, asyncContext, asyncContext->work); + HiLog::Debug(LABEL, "Release exit"); + return result; +} } // namespace Media -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/frameworks/kits/js/common/native_module_ohos_image.cpp b/frameworks/kits/js/common/native_module_ohos_image.cpp index bd70d78e60cdf60b51e492c40d40a8ab51c15035..7501e18c5f955805e170b969f03b53608e09a4a9 100644 --- a/frameworks/kits/js/common/native_module_ohos_image.cpp +++ b/frameworks/kits/js/common/native_module_ohos_image.cpp @@ -14,7 +14,12 @@ */ #include "native_module_ohos_image.h" +#include "hilog/log.h" +using OHOS::HiviewDFX::HiLog; +namespace { + constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, LOG_DOMAIN, "NAPITEST"}; +} namespace OHOS { namespace Media{ /* @@ -22,8 +27,12 @@ namespace Media{ */ static napi_value Export(napi_env env, napi_value exports) { - + HiLog::Error(LABEL, "ImagePackerNapi CALL"); + ImagePackerNapi::Init(env, exports); + HiLog::Error(LABEL, "PixelMapNapi CALL"); PixelMapNapi::Init(env, exports); + HiLog::Error(LABEL, "ImageSourceNapi CALL"); + ImageSourceNapi::Init(env, exports); return exports; } diff --git a/frameworks/kits/js/common/pixel_map_napi.cpp b/frameworks/kits/js/common/pixel_map_napi.cpp index 3aa4d78609fb042f0bd4f8846ca83a024af426ce..0fff3475406f72dd473a66af3122b870653b020d 100644 --- a/frameworks/kits/js/common/pixel_map_napi.cpp +++ b/frameworks/kits/js/common/pixel_map_napi.cpp @@ -22,6 +22,11 @@ using OHOS::HiviewDFX::HiLog; namespace { constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, LOG_DOMAIN, "PixelMapNapi"}; + constexpr uint32_t NUM_0 = 0; + constexpr uint32_t NUM_1 = 1; + constexpr uint32_t NUM_2 = 2; + constexpr uint32_t NUM_3 = 3; + constexpr uint32_t NUM_4 = 4; } namespace OHOS { @@ -52,12 +57,12 @@ struct PixelMapAsyncContext { PositionArea area; std::shared_ptr rPixelMap; uint32_t resultUint32; + ImageInfo imageInfo; }; static PixelFormat ParsePixlForamt(int32_t val) { - if(val <= static_cast(PixelFormat::CMYK)) - { + if (val <= static_cast(PixelFormat::CMYK)) { return PixelFormat(val); } @@ -66,8 +71,7 @@ static PixelFormat ParsePixlForamt(int32_t val) static AlphaType ParseAlphaType(int32_t val) { - if(val <= static_cast(AlphaType::IMAGE_ALPHA_TYPE_UNPREMUL)) - { + if (val <= static_cast(AlphaType::IMAGE_ALPHA_TYPE_UNPREMUL)) { return AlphaType(val); } @@ -77,8 +81,7 @@ static AlphaType ParseAlphaType(int32_t val) static ScaleMode ParseScaleMode(int32_t val) { - if(val <= static_cast(ScaleMode::CENTER_CROP)) - { + if (val <= static_cast(ScaleMode::CENTER_CROP)) { return ScaleMode(val); } @@ -87,13 +90,11 @@ static ScaleMode ParseScaleMode(int32_t val) static bool parseSize(napi_env env, napi_value root, Size* size) { - if(!GET_INT32_BY_NAME(root, "height", size->height)) - { + if (!GET_INT32_BY_NAME(root, "height", size->height)) { return false; } - if(!GET_INT32_BY_NAME(root, "width", size->width)) - { + if (!GET_INT32_BY_NAME(root, "width", size->width)) { return false; } @@ -105,39 +106,33 @@ static bool parseInitializationOptions(napi_env env, napi_value root, Initializa uint32_t tmpNumber = 0; napi_value tmpValue = nullptr; - if(!GET_BOOL_BY_NAME(root, "editable", opts->editable)) - { + if (!GET_BOOL_BY_NAME(root, "editable", opts->editable)) { return false; } - if(!GET_UINT32_BY_NAME(root, "alphaType", tmpNumber)) - { + if (!GET_UINT32_BY_NAME(root, "alphaType", tmpNumber)) { return false; } opts->alphaType = ParseAlphaType(tmpNumber); tmpNumber = 0; - if(!GET_UINT32_BY_NAME(root, "pixelFormat", tmpNumber)) - { + if (!GET_UINT32_BY_NAME(root, "pixelFormat", tmpNumber)) { return false; } opts->pixelFormat = ParsePixlForamt(tmpNumber); tmpNumber = 0; - if(!GET_UINT32_BY_NAME(root, "scaleMode", tmpNumber)) - { + if (!GET_UINT32_BY_NAME(root, "scaleMode", tmpNumber)) { return false; } opts->scaleMode = ParseScaleMode(tmpNumber); - if(!GET_NODE_BY_NAME(root, "size", tmpValue)) - { + if (!GET_NODE_BY_NAME(root, "size", tmpValue)) { return false; } - if(!parseSize(env, tmpValue, &(opts->size))) - { + if (!parseSize(env, tmpValue, &(opts->size))) { return false; } return true; @@ -147,28 +142,23 @@ static bool parseRegion(napi_env env, napi_value root, Rect* region) { napi_value tmpValue = nullptr; - if(!GET_INT32_BY_NAME(root, "x", region->left)) - { + if (!GET_INT32_BY_NAME(root, "x", region->left)) { return false; } - if(!GET_INT32_BY_NAME(root, "y", region->top)) - { + if (!GET_INT32_BY_NAME(root, "y", region->top)) { return false; } - if(!GET_NODE_BY_NAME(root, "size", tmpValue)) - { + if (!GET_NODE_BY_NAME(root, "size", tmpValue)) { return false; } - if(!GET_INT32_BY_NAME(tmpValue, "height", region->height)) - { + if (!GET_INT32_BY_NAME(tmpValue, "height", region->height)) { return false; } - if(!GET_INT32_BY_NAME(tmpValue, "width", region->width)) - { + if (!GET_INT32_BY_NAME(tmpValue, "width", region->width)) { return false; } @@ -179,28 +169,23 @@ static bool parsePositionArea(napi_env env, napi_value root, PositionArea* area) { napi_value tmpValue = nullptr; - if(!GET_BUFFER_BY_NAME(root, "pixels", area->pixels, area->size)) - { + if (!GET_BUFFER_BY_NAME(root, "pixels", area->pixels, area->size)) { return false; } - if(!GET_UINT32_BY_NAME(root, "offset", area->offset)) - { + if (!GET_UINT32_BY_NAME(root, "offset", area->offset)) { return false; } - if(!GET_UINT32_BY_NAME(root, "stride", area->stride)) - { + if (!GET_UINT32_BY_NAME(root, "stride", area->stride)) { return false; } - - if(!GET_NODE_BY_NAME(root, "region", tmpValue)) - { + + if (!GET_NODE_BY_NAME(root, "region", tmpValue)) { return false; } - - if(!parseRegion(env, tmpValue, &(area->region))) - { + + if (!parseRegion(env, tmpValue, &(area->region))) { return false; } return true; @@ -208,26 +193,26 @@ static bool parsePositionArea(napi_env env, napi_value root, PositionArea* area) static void CommonCallbackRoutine(napi_env env, PixelMapAsyncContext* &asyncContext, const napi_value &valueParam) { - napi_value result[2] = {0}; + napi_value result[NUM_2] = {0}; napi_value retVal; napi_value callback = nullptr; - napi_get_undefined(env, &result[0]); - napi_get_undefined(env, &result[1]); + napi_get_undefined(env, &result[NUM_0]); + napi_get_undefined(env, &result[NUM_1]); if (asyncContext->status == SUCCESS) { - result[1] = valueParam; + result[NUM_1] = valueParam; } if (asyncContext->deferred) { if (asyncContext->status == SUCCESS) { - napi_resolve_deferred(env, asyncContext->deferred, result[1]); + napi_resolve_deferred(env, asyncContext->deferred, result[NUM_1]); } else { - napi_reject_deferred(env, asyncContext->deferred, result[0]); + napi_reject_deferred(env, asyncContext->deferred, result[NUM_0]); } } else { napi_get_reference_value(env, asyncContext->callbackRef, &callback); - napi_call_function(env, nullptr, callback, 2, result, &retVal); + napi_call_function(env, nullptr, callback, NUM_2, result, &retVal); napi_delete_reference(env, asyncContext->callbackRef); } @@ -257,14 +242,11 @@ STATIC_COMPLETE_FUNC(Uint32Result) status = napi_create_int32(env, context->resultUint32, &result); - if(!IMG_IS_OK(status)) - { + if (!IMG_IS_OK(status)) { context->status = ERROR; HiLog::Error(LABEL, "napi_create_int32 failed!"); napi_get_undefined(env, &result); - } - else - { + } else { context->status = SUCCESS; } @@ -279,13 +261,11 @@ PixelMapNapi::PixelMapNapi() PixelMapNapi::~PixelMapNapi() { - if(nativePixelMap_ != nullptr) - { + if (nativePixelMap_ != nullptr) { nativePixelMap_ = nullptr; } - if (wrapper_ != nullptr) - { + if (wrapper_ != nullptr) { napi_delete_reference(env_, wrapper_); } } @@ -347,8 +327,7 @@ std::shared_ptr PixelMapNapi::GetPixelMap(napi_env env, napi_value pix napi_status status = napi_unwrap(env, pixelmap, reinterpret_cast(&pixelMapNapi)); - if(IMG_IS_OK(status)) - { + if (IMG_IS_OK(status)) { return pixelMapNapi->nativePixelMap_; } @@ -389,8 +368,7 @@ void PixelMapNapi::Destructor(napi_env env, void *nativeObject, void *finalize) { PixelMapNapi *pixelMapNapi = reinterpret_cast(nativeObject); - if (IMG_NOT_NULL(pixelMapNapi)) - { + if (IMG_NOT_NULL(pixelMapNapi)) { pixelMapNapi->~PixelMapNapi(); } } @@ -403,12 +381,9 @@ STATIC_EXEC_FUNC(CreatePixelMap) context->rPixelMap = std::move(pixelmap); - if(IMG_NOT_NULL(context->rPixelMap)) - { + if (IMG_NOT_NULL(context->rPixelMap)) { context->status = SUCCESS; - } - else - { + } else { context->status = ERROR; } } @@ -425,18 +400,16 @@ void PixelMapNapi::CreatePixelMapComplete(napi_env env, napi_status status, void if (IMG_IS_OK(status)) { sPixelMap_ = context->rPixelMap; - status = napi_new_instance(env, constructor, 0, nullptr, &result); + status = napi_new_instance(env, constructor, NUM_0, nullptr, &result); } - if(!IMG_IS_OK(status)) - { + if (!IMG_IS_OK(status)) { context->status = ERROR; HiLog::Error(LABEL, "New instance could not be obtained"); napi_get_undefined(env, &result); } CommonCallbackRoutine(env, context, result); - } napi_value PixelMapNapi::CreatePixelMap(napi_env env, napi_callback_info info) @@ -448,28 +421,27 @@ napi_value PixelMapNapi::CreatePixelMap(napi_env env, napi_callback_info info) napi_status status; napi_value thisVar = nullptr; - napi_value argValue[4] = {0}; - size_t argCount = 4; + napi_value argValue[NUM_4] = {0}; + size_t argCount = NUM_4; HiLog::Debug(LABEL, "CreatePixelMap IN"); IMG_JS_ARGS(env, info, status, argCount, argValue, thisVar); // we are static method! - // this Var is nullptr here + // thisVar is nullptr here IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), nullptr, HiLog::Error(LABEL, "fail to napi_get_cb_info")); - std::unique_ptr asyncContext = std::make_unique(); - status = napi_get_arraybuffer_info(env, argValue[0], &(asyncContext->colorsBuffer), &(asyncContext->colorsBufferSize)); + status = napi_get_arraybuffer_info(env, argValue[NUM_0], &(asyncContext->colorsBuffer), + &(asyncContext->colorsBufferSize)); IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), nullptr, HiLog::Error(LABEL, "colors mismatch")); IMG_NAPI_CHECK_RET_D(parseInitializationOptions(env, argValue[1], &(asyncContext->opts)), nullptr, HiLog::Error(LABEL, "InitializationOptions mismatch")); - - if(argCount == 3 && ImageNapiUtils::getType(env, argValue[argCount -1]) == napi_function) - { - napi_create_reference(env, argValue[argCount -1], refCount, &asyncContext->callbackRef); + + if (argCount == NUM_3 && ImageNapiUtils::getType(env, argValue[argCount - 1]) == napi_function) { + napi_create_reference(env, argValue[argCount - 1], refCount, &asyncContext->callbackRef); } if (asyncContext->callbackRef == nullptr) { @@ -488,7 +460,6 @@ napi_value PixelMapNapi::CreatePixelMap(napi_env env, napi_callback_info info) napi_value PixelMapNapi::CreatePixelMap(napi_env env, std::shared_ptr pixelmap) { - napi_value constructor = nullptr; napi_value result = nullptr; napi_status status; @@ -498,11 +469,10 @@ napi_value PixelMapNapi::CreatePixelMap(napi_env env, std::shared_ptr if (IMG_IS_OK(status)) { sPixelMap_ = pixelmap; - status = napi_new_instance(env, constructor, 0, nullptr, &result); + status = napi_new_instance(env, constructor, NUM_0, nullptr, &result); } - if(!IMG_IS_OK(status)) - { + if (!IMG_IS_OK(status)) { HiLog::Error(LABEL, "CreatePixelMap | New instance could not be obtained"); napi_get_undefined(env, &result); } @@ -544,8 +514,8 @@ napi_value PixelMapNapi::ReadPixelsToBuffer(napi_env env, napi_callback_info inf int32_t refCount = 1; napi_status status; napi_value thisVar = nullptr; - napi_value argValue[2] = {0}; - size_t argCount = 2; + napi_value argValue[NUM_2] = {0}; + size_t argCount = NUM_2; HiLog::Debug(LABEL, "ReadPixelsToBuffer IN"); IMG_JS_ARGS(env, info, status, argCount, argValue, thisVar); @@ -554,7 +524,7 @@ napi_value PixelMapNapi::ReadPixelsToBuffer(napi_env env, napi_callback_info inf std::unique_ptr asyncContext = std::make_unique(); status = napi_unwrap(env, thisVar, reinterpret_cast(&asyncContext->nConstructor)); - + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->nConstructor), nullptr, HiLog::Error(LABEL, "fail to unwrap context")); @@ -563,14 +533,13 @@ napi_value PixelMapNapi::ReadPixelsToBuffer(napi_env env, napi_callback_info inf IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->rPixelMap), nullptr, HiLog::Error(LABEL, "empty native pixelmap")); - status = napi_get_arraybuffer_info(env, argValue[0], + status = napi_get_arraybuffer_info(env, argValue[NUM_0], &(asyncContext->colorsBuffer), &(asyncContext->colorsBufferSize)); IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), nullptr, HiLog::Error(LABEL, "colors mismatch")); - - if(argCount == 2 && ImageNapiUtils::getType(env, argValue[argCount -1]) == napi_function) - { - napi_create_reference(env, argValue[argCount -1], refCount, &asyncContext->callbackRef); + + if (argCount == NUM_2 && ImageNapiUtils::getType(env, argValue[argCount - 1]) == napi_function) { + napi_create_reference(env, argValue[argCount - 1], refCount, &asyncContext->callbackRef); } if (asyncContext->callbackRef == nullptr) { @@ -602,8 +571,8 @@ napi_value PixelMapNapi::ReadPixels(napi_env env, napi_callback_info info) int32_t refCount = 1; napi_status status; napi_value thisVar = nullptr; - napi_value argValue[2] = {0}; - size_t argCount = 2; + napi_value argValue[NUM_2] = {0}; + size_t argCount = NUM_2; HiLog::Debug(LABEL, "ReadPixels IN"); IMG_JS_ARGS(env, info, status, argCount, argValue, thisVar); @@ -612,7 +581,7 @@ napi_value PixelMapNapi::ReadPixels(napi_env env, napi_callback_info info) std::unique_ptr asyncContext = std::make_unique(); status = napi_unwrap(env, thisVar, reinterpret_cast(&asyncContext->nConstructor)); - + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->nConstructor), nullptr, HiLog::Error(LABEL, "fail to unwrap context")); @@ -620,13 +589,12 @@ napi_value PixelMapNapi::ReadPixels(napi_env env, napi_callback_info info) IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->rPixelMap), nullptr, HiLog::Error(LABEL, "empty native pixelmap")); - - IMG_NAPI_CHECK_RET_D(parsePositionArea(env, argValue[0], &(asyncContext->area)), + + IMG_NAPI_CHECK_RET_D(parsePositionArea(env, argValue[NUM_0], &(asyncContext->area)), nullptr, HiLog::Error(LABEL, "fail to parse position area")); - if(argCount == 2 && ImageNapiUtils::getType(env, argValue[argCount -1]) == napi_function) - { - napi_create_reference(env, argValue[argCount -1], refCount, &asyncContext->callbackRef); + if (argCount == NUM_2 && ImageNapiUtils::getType(env, argValue[argCount - 1]) == napi_function) { + napi_create_reference(env, argValue[argCount - 1], refCount, &asyncContext->callbackRef); } if (asyncContext->callbackRef == nullptr) { @@ -657,8 +625,8 @@ napi_value PixelMapNapi::WritePixels(napi_env env, napi_callback_info info) int32_t refCount = 1; napi_status status; napi_value thisVar = nullptr; - napi_value argValue[2] = {0}; - size_t argCount = 2; + napi_value argValue[NUM_2] = {0}; + size_t argCount = NUM_2; HiLog::Debug(LABEL, "WritePixels IN"); IMG_JS_ARGS(env, info, status, argCount, argValue, thisVar); @@ -667,7 +635,7 @@ napi_value PixelMapNapi::WritePixels(napi_env env, napi_callback_info info) std::unique_ptr asyncContext = std::make_unique(); status = napi_unwrap(env, thisVar, reinterpret_cast(&asyncContext->nConstructor)); - + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->nConstructor), nullptr, HiLog::Error(LABEL, "fail to unwrap context")); @@ -675,13 +643,12 @@ napi_value PixelMapNapi::WritePixels(napi_env env, napi_callback_info info) IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->rPixelMap), nullptr, HiLog::Error(LABEL, "empty native pixelmap")); - - IMG_NAPI_CHECK_RET_D(parsePositionArea(env, argValue[0], &(asyncContext->area)), + + IMG_NAPI_CHECK_RET_D(parsePositionArea(env, argValue[NUM_0], &(asyncContext->area)), nullptr, HiLog::Error(LABEL, "fail to parse position area")); - if(argCount == 2 && ImageNapiUtils::getType(env, argValue[argCount -1]) == napi_function) - { - napi_create_reference(env, argValue[argCount -1], refCount, &asyncContext->callbackRef); + if (argCount == NUM_2 && ImageNapiUtils::getType(env, argValue[argCount - 1]) == napi_function) { + napi_create_reference(env, argValue[argCount - 1], refCount, &asyncContext->callbackRef); } if (asyncContext->callbackRef == nullptr) { @@ -713,8 +680,8 @@ napi_value PixelMapNapi::WriteBufferToPixels(napi_env env, napi_callback_info in int32_t refCount = 1; napi_status status; napi_value thisVar = nullptr; - napi_value argValue[2] = {0}; - size_t argCount = 2; + napi_value argValue[NUM_2] = {0}; + size_t argCount = NUM_2; HiLog::Debug(LABEL, "WriteBufferToPixels IN"); IMG_JS_ARGS(env, info, status, argCount, argValue, thisVar); @@ -723,7 +690,7 @@ napi_value PixelMapNapi::WriteBufferToPixels(napi_env env, napi_callback_info in std::unique_ptr asyncContext = std::make_unique(); status = napi_unwrap(env, thisVar, reinterpret_cast(&asyncContext->nConstructor)); - + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->nConstructor), nullptr, HiLog::Error(LABEL, "fail to unwrap context")); @@ -731,15 +698,14 @@ napi_value PixelMapNapi::WriteBufferToPixels(napi_env env, napi_callback_info in IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->rPixelMap), nullptr, HiLog::Error(LABEL, "empty native pixelmap")); - status = napi_get_arraybuffer_info(env, argValue[0], + status = napi_get_arraybuffer_info(env, argValue[NUM_0], &(asyncContext->colorsBuffer), &(asyncContext->colorsBufferSize)); - + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), nullptr, HiLog::Error(LABEL, "fail to get buffer info")); - if(argCount == 2 && ImageNapiUtils::getType(env, argValue[argCount -1]) == napi_function) - { - napi_create_reference(env, argValue[argCount -1], refCount, &asyncContext->callbackRef); + if (argCount == NUM_2 && ImageNapiUtils::getType(env, argValue[argCount - 1]) == napi_function) { + napi_create_reference(env, argValue[argCount - 1], refCount, &asyncContext->callbackRef); } if (asyncContext->callbackRef == nullptr) { @@ -752,8 +718,8 @@ napi_value PixelMapNapi::WriteBufferToPixels(napi_env env, napi_callback_info in [](napi_env env, void *data) { auto context = static_cast(data); - context->status = context->rPixelMap->WritePixels(static_cast(context->colorsBuffer), context->colorsBufferSize); - + context->status = context->rPixelMap->WritePixels(static_cast(context->colorsBuffer), + context->colorsBufferSize); }, EmptyResultComplete, asyncContext, asyncContext->work); IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), @@ -761,10 +727,77 @@ napi_value PixelMapNapi::WriteBufferToPixels(napi_env env, napi_callback_info in return result; } +STATIC_COMPLETE_FUNC(GetImageInfo) +{ + HiLog::Debug(LABEL, "[PixelMap]GetImageInfoComplete IN"); + napi_value result = nullptr; + napi_create_object(env, &result); + auto context = static_cast(data); + napi_value size = nullptr; + napi_create_object(env, &size); + napi_value sizeWith = nullptr; + napi_create_int32(env, context->imageInfo.size.width, &sizeWith); + napi_set_named_property(env, size, "width", sizeWith); + napi_value sizeHeight = nullptr; + napi_create_int32(env, context->imageInfo.size.height, &sizeHeight); + napi_set_named_property(env, size, "height", sizeHeight); + napi_set_named_property(env, result, "size", size); + napi_value pixelFormatValue = nullptr; + napi_create_int32(env, static_cast(context->imageInfo.pixelFormat), &pixelFormatValue); + napi_set_named_property(env, result, "pixelFormat", pixelFormatValue); + napi_value colorSpaceValue = nullptr; + napi_create_int32(env, static_cast(context->imageInfo.colorSpace), &colorSpaceValue); + napi_set_named_property(env, result, "colorSpace", colorSpaceValue); + napi_value alphaTypeValue = nullptr; + napi_create_int32(env, static_cast(context->imageInfo.alphaType), &alphaTypeValue); + napi_set_named_property(env, result, "alphaType", alphaTypeValue); + if (!IMG_IS_OK(status)) { + context->status = ERROR; + HiLog::Error(LABEL, "napi_create_int32 failed!"); + napi_get_undefined(env, &result); + } else { + context->status = SUCCESS; + } + HiLog::Debug(LABEL, "[PixelMap]GetImageInfoComplete OUT"); + CommonCallbackRoutine(env, context, result); +} napi_value PixelMapNapi::GetImageInfo(napi_env env, napi_callback_info info) { + napi_value result = nullptr; + napi_get_undefined(env, &result); + int32_t refCount = 1; + napi_status status; + napi_value thisVar = nullptr; + napi_value argValue[NUM_1] = {0}; + size_t argCount = 1; HiLog::Debug(LABEL, "GetImageInfo IN"); - return nullptr; + IMG_JS_ARGS(env, info, status, argCount, argValue, thisVar); + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), nullptr, HiLog::Error(LABEL, "fail to napi_get_cb_info")); + std::unique_ptr asyncContext = std::make_unique(); + status = napi_unwrap(env, thisVar, reinterpret_cast(&asyncContext->nConstructor)); + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->nConstructor), + nullptr, HiLog::Error(LABEL, "fail to unwrap context")); + asyncContext->rPixelMap = asyncContext->nConstructor->nativePixelMap_; + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->rPixelMap), + nullptr, HiLog::Error(LABEL, "empty native pixelmap")); + if (argCount == NUM_1 && ImageNapiUtils::getType(env, argValue[argCount - 1]) == napi_function) { + napi_create_reference(env, argValue[argCount - 1], refCount, &asyncContext->callbackRef); + } + if (asyncContext->callbackRef == nullptr) { + napi_create_promise(env, &(asyncContext->deferred), &result); + } else { + napi_get_undefined(env, &result); + } + IMG_CREATE_CREATE_ASYNC_WORK(env, status, "GetImageInfo", + [](napi_env env, void *data) + { + auto context = static_cast(data); + context->rPixelMap->GetImageInfo(context->imageInfo); + context->status = SUCCESS; + }, GetImageInfoComplete, asyncContext, asyncContext->work); + IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), + nullptr, HiLog::Error(LABEL, "fail to create async work")); + return result; } napi_value PixelMapNapi::GetBytesNumberPerRow(napi_env env, napi_callback_info info) @@ -775,8 +808,8 @@ napi_value PixelMapNapi::GetBytesNumberPerRow(napi_env env, napi_callback_info i int32_t refCount = 1; napi_status status; napi_value thisVar = nullptr; - napi_value argValue[1] = {0}; - size_t argCount = 1; + napi_value argValue[NUM_1] = {0}; + size_t argCount = NUM_1; HiLog::Debug(LABEL, "GetBytesNumberPerRow IN"); IMG_JS_ARGS(env, info, status, argCount, argValue, thisVar); @@ -785,7 +818,7 @@ napi_value PixelMapNapi::GetBytesNumberPerRow(napi_env env, napi_callback_info i std::unique_ptr asyncContext = std::make_unique(); status = napi_unwrap(env, thisVar, reinterpret_cast(&asyncContext->nConstructor)); - + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->nConstructor), nullptr, HiLog::Error(LABEL, "fail to unwrap context")); @@ -794,9 +827,8 @@ napi_value PixelMapNapi::GetBytesNumberPerRow(napi_env env, napi_callback_info i IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->rPixelMap), nullptr, HiLog::Error(LABEL, "empty native pixelmap")); - if(argCount == 1 && ImageNapiUtils::getType(env, argValue[argCount -1]) == napi_function) - { - napi_create_reference(env, argValue[argCount -1], refCount, &asyncContext->callbackRef); + if (argCount == 1 && ImageNapiUtils::getType(env, argValue[argCount - 1]) == napi_function) { + napi_create_reference(env, argValue[argCount - 1], refCount, &asyncContext->callbackRef); } if (asyncContext->callbackRef == nullptr) { @@ -806,12 +838,10 @@ napi_value PixelMapNapi::GetBytesNumberPerRow(napi_env env, napi_callback_info i } IMG_CREATE_CREATE_ASYNC_WORK(env, status, "GetBytesNumberPerRow", - [](napi_env env, void *data) - { + [](napi_env env, void *data) { auto context = static_cast(data); context->resultUint32 = context->rPixelMap->GetRowBytes(); context->status = SUCCESS; - }, Uint32ResultComplete, asyncContext, asyncContext->work); IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), @@ -837,7 +867,7 @@ napi_value PixelMapNapi::GetPixelBytesNumber(napi_env env, napi_callback_info in std::unique_ptr asyncContext = std::make_unique(); status = napi_unwrap(env, thisVar, reinterpret_cast(&asyncContext->nConstructor)); - + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->nConstructor), nullptr, HiLog::Error(LABEL, "fail to unwrap context")); @@ -846,9 +876,8 @@ napi_value PixelMapNapi::GetPixelBytesNumber(napi_env env, napi_callback_info in IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, asyncContext->rPixelMap), nullptr, HiLog::Error(LABEL, "empty native pixelmap")); - if(argCount == 1 && ImageNapiUtils::getType(env, argValue[argCount -1]) == napi_function) - { - napi_create_reference(env, argValue[argCount -1], refCount, &asyncContext->callbackRef); + if (argCount == 1 && ImageNapiUtils::getType(env, argValue[argCount - 1]) == napi_function) { + napi_create_reference(env, argValue[argCount - 1], refCount, &asyncContext->callbackRef); } if (asyncContext->callbackRef == nullptr) { @@ -863,7 +892,6 @@ napi_value PixelMapNapi::GetPixelBytesNumber(napi_env env, napi_callback_info in auto context = static_cast(data); context->resultUint32 = context->rPixelMap->GetByteCount(); context->status = SUCCESS; - }, Uint32ResultComplete, asyncContext, asyncContext->work); IMG_NAPI_CHECK_RET_D(IMG_IS_OK(status), @@ -886,13 +914,12 @@ napi_value PixelMapNapi::Release(napi_env env, napi_callback_info info) std::unique_ptr pixelMapNapi = std::make_unique(); status = napi_unwrap(env, thisVar, reinterpret_cast(&pixelMapNapi)); - + IMG_NAPI_CHECK_RET_D(IMG_IS_READY(status, pixelMapNapi), result, HiLog::Error(LABEL, "fail to unwrap context")); pixelMapNapi->nativePixelMap_= nullptr; return result; } - } // namespace Media } // namespace OHOS diff --git a/interfaces/innerkits/BUILD.gn b/interfaces/innerkits/BUILD.gn index bf893f776a2cc0dc5d2b8fb8f7fe9493fbd1992a..0543d8531f90fb70dcdda9d51d770a98079f86e6 100644 --- a/interfaces/innerkits/BUILD.gn +++ b/interfaces/innerkits/BUILD.gn @@ -66,31 +66,14 @@ ohos_copy("image_declaration") { ohos_shared_library("image") { public_configs = [ ":image_external_config" ] sources = [ - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/codec/src/image_packer.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/codec/src/image_packer_ex.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/codec/src/image_source.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/common/src/incremental_pixel_map.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/common/src/pixel_map.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/common/src/pixel_map_parcel.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/converter/src/basic_transformer.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/converter/src/matrix.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/converter/src/pixel_convert.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/converter/src/post_proc.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/converter/src/scan_line_filter.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/buffer_packer_stream.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/buffer_source_stream.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/file_packer_stream.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/file_source_stream.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/incremental_source_stream.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/istream_source_stream.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/ostream_packer_stream.cpp", - - #"//foundation/multimedia/image_standard/frameworks/kits/js/common/image_source_napi.cpp", "//foundation/multimedia/image_standard/frameworks/kits/js/common/image_napi_utils.cpp", + "//foundation/multimedia/image_standard/frameworks/kits/js/common/image_packer_napi.cpp", + "//foundation/multimedia/image_standard/frameworks/kits/js/common/image_source_napi.cpp", "//foundation/multimedia/image_standard/frameworks/kits/js/common/native_module_ohos_image.cpp", "//foundation/multimedia/image_standard/frameworks/kits/js/common/pixel_map_napi.cpp", ] deps = [ + ":image_native", "//foundation/ace/napi:ace_napi", "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/pixelconverter:pixelconvertadapter", "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/utils:image_utils", @@ -130,11 +113,6 @@ ohos_shared_library("image_native") { "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/incremental_source_stream.cpp", "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/istream_source_stream.cpp", "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/ostream_packer_stream.cpp", - - #"//foundation/multimedia/image_standard/frameworks/kits/js/common/image_source_napi.cpp", - "//foundation/multimedia/image_standard/frameworks/kits/js/common/image_napi_utils.cpp", - "//foundation/multimedia/image_standard/frameworks/kits/js/common/native_module_ohos_image.cpp", - "//foundation/multimedia/image_standard/frameworks/kits/js/common/pixel_map_napi.cpp", ] if (use_mingw_win) { @@ -202,31 +180,14 @@ ohos_static_library("image_static_napi") { public_configs = [ ":image_external_config" ] sources = [ - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/codec/src/image_packer.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/codec/src/image_packer_ex.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/codec/src/image_source.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/common/src/incremental_pixel_map.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/common/src/pixel_map.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/common/src/pixel_map_parcel.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/converter/src/basic_transformer.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/converter/src/matrix.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/converter/src/pixel_convert.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/converter/src/post_proc.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/converter/src/scan_line_filter.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/buffer_packer_stream.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/buffer_source_stream.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/file_packer_stream.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/file_source_stream.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/incremental_source_stream.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/istream_source_stream.cpp", - "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/ostream_packer_stream.cpp", - - #"//foundation/multimedia/image_standard/frameworks/kits/js/common/image_source_napi.cpp", "//foundation/multimedia/image_standard/frameworks/kits/js/common/image_napi_utils.cpp", + "//foundation/multimedia/image_standard/frameworks/kits/js/common/image_packer_napi.cpp", + "//foundation/multimedia/image_standard/frameworks/kits/js/common/image_source_napi.cpp", "//foundation/multimedia/image_standard/frameworks/kits/js/common/native_module_ohos_image.cpp", "//foundation/multimedia/image_standard/frameworks/kits/js/common/pixel_map_napi.cpp", ] deps = [ + ":image_native", "//foundation/ace/napi:ace_napi", "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/pixelconverter:pixelconvertadapter", "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/utils:image_utils", @@ -258,11 +219,6 @@ ohos_static_library("image_static") { "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/incremental_source_stream.cpp", "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/istream_source_stream.cpp", "//foundation/multimedia/image_standard/frameworks/innerkitsimpl/stream/src/ostream_packer_stream.cpp", - - #"//foundation/multimedia/image_standard/frameworks/kits/js/common/image_source_napi.cpp", - "//foundation/multimedia/image_standard/frameworks/kits/js/common/image_napi_utils.cpp", - "//foundation/multimedia/image_standard/frameworks/kits/js/common/native_module_ohos_image.cpp", - "//foundation/multimedia/image_standard/frameworks/kits/js/common/pixel_map_napi.cpp", ] if (use_mingw_win) { diff --git a/interfaces/innerkits/include/image_source.h b/interfaces/innerkits/include/image_source.h index 74195469120d406dd03dceaccfd76bb00124b39c..04021861a14604ec2cccdeb30cd8259323c2d0c7 100644 --- a/interfaces/innerkits/include/image_source.h +++ b/interfaces/innerkits/include/image_source.h @@ -131,6 +131,8 @@ public: const SourceOptions &opts, uint32_t &errorCode); NATIVEEXPORT static std::unique_ptr CreateImageSource(const std::string &pathName, const SourceOptions &opts, uint32_t &errorCode); + NATIVEEXPORT static std::unique_ptr CreateImageSource(const int fd, const SourceOptions &opts, + uint32_t &errorCode); NATIVEEXPORT static std::unique_ptr CreateIncrementalImageSource(const IncrementalSourceOptions &opts, uint32_t &errorCode); @@ -159,6 +161,7 @@ public: NATIVEEXPORT void RemoveDecodeListener(DecodeListener *listener); NATIVEEXPORT bool IsIncrementalSource(); NATIVEEXPORT uint32_t GetImagePropertyInt(uint32_t index, const std::string &key, int32_t &value); + NATIVEEXPORT uint32_t GetImagePropertyString(uint32_t index, const std::string &key, std::string &value); NATIVEEXPORT const NinePatchInfo &GetNinePatchInfo() const; NATIVEEXPORT void SetMemoryUsagePreference(const MemoryUsagePreference preference); NATIVEEXPORT MemoryUsagePreference GetMemoryUsagePreference(); diff --git a/interfaces/innerkits/include/image_type.h b/interfaces/innerkits/include/image_type.h index 36c71c2433e47cf61e8c6865653c6ecb99b6613f..0672f661ba6ee051e3b07267c3600f0a328b1993 100644 --- a/interfaces/innerkits/include/image_type.h +++ b/interfaces/innerkits/include/image_type.h @@ -158,7 +158,9 @@ struct DecodeOptions { int32_t fitDensity = 0; Rect CropRect; Size desiredSize; + Rect desiredRegion; float rotateDegrees = 0; + uint32_t rotateNewDegrees = 0; static constexpr uint32_t DEFAULT_SAMPLE_SIZE = 1; uint32_t sampleSize = DEFAULT_SAMPLE_SIZE; PixelFormat desiredPixelFormat = PixelFormat::UNKNOWN; diff --git a/interfaces/kits/js/@ohos.multimedia.image.d.ts b/interfaces/kits/js/@ohos.multimedia.image.d.ts index 1c418d018ff4672ab22a130ac14383ce7d1456f5..eb8281e294d333de2284922ddcb7ffac63a07d83 100755 --- a/interfaces/kits/js/@ohos.multimedia.image.d.ts +++ b/interfaces/kits/js/@ohos.multimedia.image.d.ts @@ -1,385 +1,924 @@ -/* -* Copyright (C) 2021 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -import { AsyncCallback } from './basic'; - -declare namespace image { - - /** - * Enumerates pixel map formats. - */ - enum PixelMapFormat { - /** - * Indicates an unknown pixel map format. - */ - UNKNOWN = 0, - - /** - * Indicates that each pixel is stored on 32 bits. Components A, R, G, and B each occupies 8 bits - * and are stored from the higher-order to the lower-order bits. - */ - ARGB_8888 = 1, - - /** - * Indicates that each pixel is stored on 16 bits. Only the R, G, and B components are encoded - * from the higher-order to the lower-order bits: red is stored with 5 bits of precision, - * green is stored with 6 bits of precision, and blue is stored with 5 bits of precision. - */ - RGB_565 = 2 - } - - /** - * Enumerates color spaces. - */ - enum ColorSpace { - /** - * Indicates an unknown color space. - */ - UNKNOWN = 0, - - /** - * Indicates the color space based on SMPTE RP 431-2-2007 and IEC 61966-2.1:1999. - */ - DISPLAY_P3 = 1, - - /** - * Indicates the standard red green blue (SRGB) color space based on IEC 61966-2.1:1999. - */ - SRGB = 2, - - /** - * Indicates the SRGB using a linear transfer function based on the IEC 61966-2.1:1999 standard. - */ - LINEAR_SRGB = 3, - - /** - * Indicates the color space based on IEC 61966-2-2:2003. - */ - EXTENDED_SRGB = 4, - - /** - * Indicates the color space based on IEC 61966-2-2:2003. - */ - LINEAR_EXTENDED_SRGB = 5, - - /** - * Indicates the color space based on the standard illuminant with D50 as the white point. - */ - GENERIC_XYZ = 6, - - /** - * Indicates the color space using CIE XYZ D50 as the profile conversion space. - */ - GENERIC_LAB = 7, - - /** - * Indicates the color space based on SMPTE ST 2065-1:2012. - */ - ACES = 8, - - /** - * Indicates the color space based on Academy S-2014-004. - */ - ACES_CG = 9, - - /** - * Indicates the color space based on Adobe RGB (1998). - */ - ADOBE_RGB_1998 = 10, - - /** - * Indicates the color space based on SMPTE RP 431-2-2007. - */ - DCI_P3 = 11, - - /** - * Indicates the color space based on Rec.ITU-R BT.709-5. - */ - ITU_709 = 12, - - /** - * Indicates the color space based on Rec.ITU-R BT.2020-1. - */ - ITU_2020 = 13, - - /** - * Indicates the color space based on ISO 22028-2:2013. - */ - ROMM_RGB = 14, - - /** - * Indicates the color space based on the NTSC 1953 standard. - */ - NTSC_1953 = 15, - - /** - * Indicates the color space based on SMPTE C. - */ - SMPTE_C = 16 - } - - /** - * Enumerates alpha types. - */ - enum AlphaType { - /** - * Indicates an unknown alpha type. - */ - UNKNOWN = 0, - - /** - * Indicates that the image has no alpha channel, or all pixels in the image are fully opaque. - */ - OPAQUE = 1, - - /** - * Indicates that RGB components of each pixel in the image are premultiplied by alpha. - */ - PREMUL = 2, - - /** - * Indicates that RGB components of each pixel in the image are independent of alpha and are not premultiplied by alpha. - */ - UNPREMUL = 3 - } - - /** - * Describes the size of an image. - */ - interface Size { - height: number; - width: number; - } - - interface Region { - size: Size; - x: number; - y: number; - } - - interface PositionArea { - pixels: ArrayBuffer; - offset: number; - stride: number; - region: Region; - } - - /** - * Describes image information. - */ - interface ImageInfo { - size: Size; - pixelFormat: PixelMapFormat; - colorSpace: ColorSpace; - alphaType: AlphaType; - } - - /** - * Describes the option for image packing. - */ - interface PackingOption { - /** - * Multipurpose Internet Mail Extensions (MIME) format of the target image, for example, image/jpeg. - */ - format: string; - - /** - * Quality of the target image. The value is an integer ranging from 0 to 100. A larger value indicates better - */ - quality: number; - } - - interface DecodingOptions { - // Indicates the sampling size based on which an image is scaled down. - sampleSize: number; - - // Indicates the rotation angle, ranging from 0 to 360 - rotateDegrees: number; - - // Specifies whether pixel values of the pixel map to be decoded can be edited. - editable: boolean; - - // Indicates the expected output size - desiredSize: Size; - - // Indicates an image area to be decoded. - desiredRegion: Region; - - // Indicates the pixel format of a decoded image, which is defined by PixelFormat. - desiredPixelFormat: PixelMapFormat; - - // reused current pixelmap buffer address for a new created pixelmap - reusedPixelMap: PixelMap; - } - - enum ScaleMode { - CENTER_CROP = 1, // Indicates the effect that scales an image to fill the target image area and center-crops the part outside the area. - FIT_TARGET_SIZE = 2, // Indicates the effect that fits the image into the target size. - } - - interface InitializationOptions { - // Indicates the expected alpha type of the pixel map to be created - alphaType: AlphaType; - - // Specifies whether pixel values of the pixel map to be created can be edited - editable: boolean; - - // Indicates the expected format of the pixel map to be created - pixelFormat: PixelMapFormat; - - // Indicates the scaling effect used when the aspect ratio of the original image is different from that of the target image - scaleMode: ScaleMode; - - // Indicates the expected size of the pixel map to be created - size: Size; - } - - /** - * Creates an ImageSource instance. - */ - function createImageSource(uri: string): ImageSource; - - // create a imagesource based on fd - function createImageSource(fd: number): ImageSource; - - // Creates an ImageSource based on a ArrayBuffer and source options. - function createImageSource(data: ArrayBuffer): ImageSource; - - // Creates a pixel map based on initialization options (such as the image size, pixel format, and alpha type) - // and the data source described by a pixel color array, start offset, and number of pixels in a row. - function createPixelMap(colors: ArrayBuffer, opts: InitializationOptions): Promise; - function createPixelMap(colors: ArrayBuffer, opts: InitializationOptions, callback: AsyncCallback): void; - - - function createIncrementalSource(data: ArrayBuffer): ImageSource; - - /** - * Creates an ImagePacker instance. - */ - function createImagePacker(): ImagePacker; - - interface PixelMap { - // read all pixels to an buffer - readPixelsToBuffer(dst: ArrayBuffer): Promise; - readPixelsToBuffer(dst: ArrayBuffer, callback: AsyncCallback): void; - - // read pixels from a specified area into an buffer - readPixels(area: PositionArea): Promise>; - readPixels(area: PositionArea, callback: AsyncCallback>): void; - - // write pixels to a specified area - writePixels(area: PositionArea): Promise; - writePixels(area: PositionArea, callback: AsyncCallback): void; - - // write array buffer to pixelmap - writeBufferToPixels(src: ArrayBuffer): Promise; - writeBufferToPixels(src: ArrayBuffer, callback: AsyncCallback): void; - - // obtains basic image information. - getImageInfo(): Promise; - getImageInfo(callback: AsyncCallback): void; - - // get bytes number per row. - getBytesNumberPerRow(): Promise; - getBytesNumberPerRow(callback: AsyncCallback): void; - - // get bytes buffer for a pixelmap. - getPixelBytesNumber(): Promise; - getPixelBytesNumber(callback: AsyncCallback): void; - - // release pixelmap - release(): void; - - readonly isEditable: boolean; - } - - interface ImageSource { - /** - * Obtains information about an image with the specified sequence number and uses a callback to return the result. - */ - getImageInfo(index: number, callback: AsyncCallback): void; - - /** - * Obtains information about this image and uses a callback to return the result. - */ - getImageInfo(callback: AsyncCallback): void; - - /** - * Get image information from image source. - */ - getImageInfo(index?: number): Promise; - - // Obtains the integer value of a specified property key for an image at the given index in the ImageSource. - getImagePropertyInt(index:number, key: string, defaultValue: number): Promise; - getImagePropertyInt(index:number, key: string, defaultValue: number, callback: AsyncCallback): void; - - // Obtains the string value of a specified image property key. - getImagePropertyString(key: string): Promise; - getImagePropertyString(key: string, callback: AsyncCallback): void; - - // Decodes source image data based on a specified index location in the ImageSource and creates a pixel map. - createPixelMap(index: number, options: DecodingOptions, callback: AsyncCallback): void; - createPixelMap(opts: DecodingOptions, callback: AsyncCallback): void; - - // Updates incremental data to an image data source using a byte array with specified offset and length. - updateData(data: Array, isFinal: boolean, offset?: number, length?: number): Promise; - updateData(data: Array, isFinal: boolean, offset: number, length: number, callback: AsyncCallback): void; - updateData(data: Array, isFinal: boolean, callback: AsyncCallback): void; - - /** - * Releases an ImageSource instance and uses a callback to return the result. - */ - release(callback: AsyncCallback): void; - - /** - * Releases an ImageSource instance and uses a promise to return the result. - */ - release(): Promise; - - /** - * Supported image formats. - */ - readonly supportedFormats: Array; - } - - interface ImagePacker { - /** - * Compresses or packs an image and uses a callback to return the result. - */ - packing(source: ImageSource, option: PackingOption, callback: AsyncCallback>): void; - - /** - * Compresses or packs an image and uses a promise to return the result. - */ - packing(source: ImageSource, option: PackingOption): Promise>; - - /** - * Releases an ImagePacker instance and uses a callback to return the result. - */ - release(callback: AsyncCallback): void; - - /** - * Releases an ImagePacker instance and uses a promise to return the result. - */ - release(): Promise; - - /** - * Supported image formats. - */ - readonly supportedFormats: Array; - } -} - +/* +* Copyright (C) 2021 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import { AsyncCallback } from './basic'; + +/** + * @name image + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @import import image from '@ohos.multimedia.image'; + * @devices phone, tablet, tv, wearable, car + */ +declare namespace image { + + /** + * Enumerates pixel map formats. + * RGB 1 - 999 + * YUV 1000 - 1999 + * IMAGE ENCODING 2000 - 2999 + * VIDEO ENCODING 3000 - 3999 + * @since 7 + */ + enum PixelMapFormat { + /** + * Indicates an unknown format. + */ + UNKNOWN = 0, + + /** + * Indicates that each pixel is stored on 16 bits. Only the R, G, and B components are encoded + * from the higher-order to the lower-order bits: red is stored with 5 bits of precision, + * green is stored with 6 bits of precision, and blue is stored with 5 bits of precision. + */ + RGB_565 = 2, + + /** + * Indicates that each pixel is stored on 32 bits. Components R, G, B, and A each occupies 8 bits + * and are stored from the higher-order to the lower-order bits. + */ + RGBA_8888 = 3, + } + + /** + * Enum for image formats. + * @since 8 + */ + enum ImageFormat { + /** + * YCBCR422 semi-planar format. + * @since 8 + */ + YCBCR_422_SP = 1000, + + /** + * JPEG encoding format. + * @since 8 + */ + JPEG = 2000 + } + + enum ComponentType { + YUV_Y = 1, + YUV_U = 2, + YUV_V = 3, + } + + /** + * Describes the size of an image. + */ + interface Size { + /** + * Height + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + height: number; + + /** + * Width + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + width: number; + } + + /** + * Enumerates exchangeable image file format (Exif) information types of an image. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @import import image from '@ohos.multimedia.image' + * @devices phone, tablet, tv, wearable, car + */ + enum PropertyKey { + /** + * Number of bits in each pixel of an image. + */ + BITS_PER_SAMPLE = "BitsPerSample", + + /** + * Image rotation mode. + */ + ORIENTATION = "Orientation", + + /** + * Image length. + */ + IMAGE_LENGTH = "ImageLength", + + /** + * Image width. + */ + IMAGE_WIDTH = "ImageWidth", + + /** + * GPS latitude. + */ + GPS_LATITUDE = "GPSLatitude", + + /** + * GPS longitude. + */ + GPS_LONGITUDE = "GPSLongitude", + + /** + * GPS latitude reference. For example, N indicates north latitude and S indicates south latitude. + */ + GPS_LATITUDE_REF = "GPSLatitudeRef", + + /** + * GPS longitude reference. For example, E indicates east longitude and W indicates west longitude. + */ + GPS_LONGITUDE_REF = "GPSLongitudeRef" + } + + /** + * Describes region information. + */ + interface Region { + /** + * Image size. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + size: Size; + + /** + * x-coordinate at the upper left corner of the image. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + x: number; + + /** + * y-coordinate at the upper left corner of the image. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + y: number; + } + + /** + * Describes area information in an image. + */ + interface PositionArea { + /** + * Image data that will be read or written. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + pixels: ArrayBuffer; + + /** + * Offset for data reading. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + offset: number; + + /** + * Number of bytes to read. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + stride: number; + + /** + * Region to read. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + region: Region; + } + + /** + * Describes image information. + */ + interface ImageInfo { + /** + * Indicates image dimensions specified by a {@link Size} interface. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + size: Size; + } + + /** + * Describes the option for image packing. + */ + interface PackingOption { + /** + * Multipurpose Internet Mail Extensions (MIME) format of the target image, for example, image/jpeg. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + format: string; + + /** + * Quality of the target image. The value is an integer ranging from 0 to 100. A larger value indicates better + * image quality but larger space occupied. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + quality: number; + } + + /** + * Describes image properties. + */ + interface GetImagePropertyOptions { + /** + * Index of an image. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + index?: number; + + /** + * Default property value. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + defaultValue?: string; + } + + /** + * Describes image decoding parameters. + */ + interface DecodingOptions { + /** + * Number of image frames. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + index?: number; + + /** + * Sampling ratio of the image pixel map. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + sampleSize?: number; + + /** + * Rotation angle of the image pixel map. The value ranges from 0 to 360. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + rotate?: number; + + /** + * Whether the image pixel map is editable. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + editable?: boolean; + + /** + * Width and height of the image pixel map. The value (0, 0) indicates that the pixels are decoded + * based on the original image size. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + desiredSize?: Size; + + /** + * Cropping region of the image pixel map. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + desiredRegion?: Region; + + /** + * Data format of the image pixel map. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + */ + desiredPixelFormat?: PixelMapFormat; + } + + /** + * Options for pixelmap create. + * @since 8 + */ + interface InitializationOptions { + /** + * Indicates the expected size of the pixel map to be created + * @since 8 + */ + size: Size; + /** + * Indicates the expected format of the pixel map to be created + * @since 8 + */ + pixelFormat?: PixelMapFormat; + /** + * Specifies whether pixel values of the pixel map to be created can be edited + * @since 8 + */ + editable?: boolean; + } + + /** + * Creates an ImageSource instance based on the URI. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param uri Image source URI. + * @return Returns the ImageSource instance if the operation is successful; returns null otherwise. + */ + function createImageSource(uri: string): ImageSource; + + /** + * Creates an ImageSource instance based on the file descriptor. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param fd ID of a file descriptor. + * @return Returns the ImageSource instance if the operation is successful; returns null otherwise. + */ + function createImageSource(fd: number): ImageSource; + + /** + * Creates an ImageSource instance based on the array buffer. + * @param data Image source data. + * @return Returns the ImageSource instance if the operation is successful; returns null otherwise. + * @since 8 + */ + function createImageSource(data: ArrayBuffer): ImageSource; + + /** + * Creates an empty PixelMap instance. + * @param data Image source data. + * @return Returns the ImageSource instance if the operation is successful; returns null otherwise. + * @since 8 + */ + function createPixelMap(options: InitializationOptions, callback: AsyncCallback): void; + function createPixelMap(options: InitializationOptions): Promise; + + /** + * Creates a PixelMap instance based on the array buffer. + * @param data Image source data. + * @return Returns the ImageSource instance if the operation is successful; returns null otherwise. + * @since 8 + */ + function createPixelMap(colors: ArrayBuffer, options: InitializationOptions, callback: AsyncCallback): void; + function createPixelMap(colors: ArrayBuffer, options: InitializationOptions): Promise; + + /** + * Creates an ImagePacker instance. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @return Returns the ImagePacker instance if the operation is successful; returns null otherwise. + */ + function createImagePacker(): ImagePacker; + + /** + * Creates an ImageReceiver instance. + * @param width The default width in pixels of the Images that this receiver will produce. + * @param height The default height in pixels of the Images that this receiver will produce. + * @param format The format of the Image that this receiver will produce. This must be one of the + * {@link ImageFormat} constants. Note that not all formats are supported, like ImageFormat.NV21. + * @param capacity The maximum number of images the user will want to access simultaneously. + */ + function createImageReceiver(width: number, height: number, format: number, capacity: number): ImageReceiver; + + /** + * Describes image color components. + * @Since 8 + */ + interface Component { + /** + * Component type. + * @Since 8 + */ + readonly componentType: ComponentType; + /** + * Row stride. + * @Since 8 + */ + readonly rowStride: number; + /** + * Pixel stride. + * @Since 8 + */ + readonly pixelStride: number; + /** + * Component buffer. + * @Since 8 + */ + readonly byteBuffer: ArrayBuffer; + } + + /** + * Provides basic image operations, including obtaining image information, and reading and writing image data. + * @Since 8 + */ + interface Image { + /** + * Sets or gets the image area to crop, default is size. + * @since 8 + */ + clipRect: Region; + + /** + * Image size. + * @since 8 + */ + readonly size: number; + + /** + * Image format. + * @since 8 + */ + readonly format: number; + + /** + * Get component buffer from image. + * @since 8 + */ + getComponent(componentType: ComponentType, callback: AsyncCallback): void; + getComponent(componentType: ComponentType): Promise; + + /** + * Release current image to receive another. + * @since 8 + */ + release(callback: AsyncCallback): void; + release(): Promise; + } + + /** + * Image receiver object. + * @Since 8 + */ + interface ImageReceiver { + /** + * Image size. + * @Since 8 + */ + readonly size: Size; + + /** + * Image capacity. + * @Since 8 + */ + readonly capacity: number; + + /** + * Image format. + * @Since 8 + */ + readonly format: ImageFormat; + + /** + * get an id which indicates a surface and can be used to set to Camera or other component can receive a surface + * @Since 8 + */ + getReceivingSurfaceId(callback: AsyncCallback): void; + getReceivingSurfaceId(): Promise; + + /** + * Get lasted image from receiver + * @since 8 + */ + readLatestImage(callback: AsyncCallback): void; + readLatestImage(): Promise; + + /** + * Get next image from receiver + * @since 8 + */ + readNextImage(callback: AsyncCallback): void; + readNextImage(): Promise; + + /** + * Subscribe callback when receiving an image + * @since 8 + */ + on(type: 'imageArrival', callback: AsyncCallback): void; + + /** + * Release instance. + * @since 8 + */ + release(callback: AsyncCallback): void; + release(): Promise; + } + + /** + * PixelMap object + * @since 7 + */ + interface PixelMap { + /** + * Whether the image pixel map can be edited. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + */ + readonly isEditable: boolean; + + /** + * Reads image pixel map data and writes the data to an ArrayBuffer. This method uses + * a promise to return the result. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param dst A buffer to which the image pixel map data will be written. + * @return A Promise instance used to return the operation result. If the operation fails, an error message is returned. + */ + readPixelsToBuffer(dst: ArrayBuffer): Promise; + + /** + * Reads image pixel map data and writes the data to an ArrayBuffer. This method uses + * a callback to return the result. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param dst A buffer to which the image pixel map data will be written. + * @param callback Callback used to return the operation result. If the operation fails, an error message is returned. + */ + readPixelsToBuffer(dst: ArrayBuffer, callback: AsyncCallback): void; + + /** + * Reads image pixel map data in an area. This method uses a promise to return the data read. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param area Area from which the image pixel map data will be read. + * @return A Promise instance used to return the operation result. If the operation fails, an error message is returned. + */ + readPixels(area: PositionArea): Promise; + + /** + * Reads image pixel map data in an area. This method uses a callback to return the data read. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param area Area from which the image pixel map data will be read. + * @param callback Callback used to return the operation result. If the operation fails, an error message is returned. + */ + readPixels(area: PositionArea, callback: AsyncCallback): void; + + /** + * Writes image pixel map data to the specified area. This method uses a promise to return + * the operation result. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param area Area to which the image pixel map data will be written. + * @return A Promise instance used to return the operation result. If the operation fails, an error message is returned. + */ + writePixels(area: PositionArea): Promise; + + /** + * Writes image pixel map data to the specified area. This method uses a callback to return + * the operation result. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param area Area to which the image pixel map data will be written. + * @param callback Callback used to return the operation result. If the operation fails, an error message is returned. + */ + writePixels(area: PositionArea, callback: AsyncCallback): void; + + /** + * Reads image data in an ArrayBuffer and writes the data to a PixelMap object. This method + * uses a promise to return the result. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param src A buffer from which the image data will be read. + * @return A Promise instance used to return the operation result. If the operation fails, an error message is returned. + */ + writeBufferToPixels(src: ArrayBuffer): Promise; + + /** + * Reads image data in an ArrayBuffer and writes the data to a PixelMap object. This method + * uses a callback to return the result. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param src A buffer from which the image data will be read. + * @param callback Callback used to return the operation result. If the operation fails, an error message is returned. + */ + writeBufferToPixels(src: ArrayBuffer, callback: AsyncCallback): void; + + /** + * Obtains pixel map information about this image. This method uses a promise to return the information. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @return A Promise instance used to return the image pixel map information. If the operation fails, an error message is returned. + */ + getImageInfo(): Promise; + + /** + * Obtains pixel map information about this image. This method uses a callback to return the information. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param callback Callback used to return the image pixel map information. If the operation fails, an error message is returned. + */ + getImageInfo(callback: AsyncCallback): void; + + /** + * Obtains the number of bytes in each line of the image pixel map. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @return Number of bytes in each line. + */ + getBytesNumberPerRow(): number; + + /** + * Obtains the number of bytes capacity. + * @return Bytes capacity. + * @since 8 + */ + getPixelBytesCapacity(): number; + + /** + * Obtains the total number of bytes of the image pixel map. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @return Total number of bytes. + */ + getPixelBytesNumber(): number; + + /** + * Releases this PixelMap object. This method uses a callback to return the result. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param callback Callback invoked for instance release. If the operation fails, an error message is returned. + */ + release(callback: AsyncCallback): void; + + /** + * Releases this PixelMap object. This method uses a promise to return the result. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @return A Promise instance used to return the instance release result. If the operation fails, an error message is returned. + */ + release(): Promise; + } + + interface ImageSource { + /** + * Obtains information about an image with the specified sequence number and uses a callback + * to return the result. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param index Sequence number of an image. + * @param callback Callback used to return the image information. + */ + getImageInfo(index: number, callback: AsyncCallback): void; + + /** + * Obtains information about this image and uses a callback to return the result. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param callback Callback used to return the image information. + */ + getImageInfo(callback: AsyncCallback): void; + + /** + * Get image information from image source. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param index Sequence number of an image. If this parameter is not specified, the default value 0 is used. + * @return A Promise instance used to return the image information. + */ + getImageInfo(index?: number): Promise; + + /** + * Creates a PixelMap object based on image decoding parameters. This method uses a promise to + * return the object. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param options Image decoding parameters. + * @return A Promise instance used to return the PixelMap object. + */ + createPixelMap(options?: DecodingOptions): Promise; + + /** + * Creates a PixelMap object. This method uses a callback to return the object. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param callback Callback used to return the PixelMap object. + */ + createPixelMap(callback: AsyncCallback): void; + + /** + * Creates a PixelMap object based on image decoding parameters. This method uses a callback to + * return the object. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param options Image decoding parameters. + * @param callback Callback used to return the PixelMap object. + */ + createPixelMap(options: DecodingOptions, callback: AsyncCallback): void; + + /** + * Obtains the value of a property in an image with the specified index. This method uses a + * promise to return the property value in a string. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param key Name of the property whose value is to be obtained. + * @param options Index of the image. + * @return A Promise instance used to return the property value. If the operation fails, the default value is returned. + */ + getImageProperty(key:string, options?: GetImagePropertyOptions): Promise; + + /** + * Obtains the value of a property in this image. This method uses a callback to return the + * property value in a string. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param key Name of the property whose value is to be obtained. + * @param callback Callback used to return the property value. If the operation fails, an error message is returned. + */ + getImageProperty(key:string, callback: AsyncCallback): void; + + /** + * Obtains the value of a property in an image with the specified index. This method uses + * a callback to return the property value in a string. + * @since 7 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param key Name of the property whose value is to be obtained. + * @param options Index of the image. + * @param callback Callback used to return the property value. If the operation fails, the default value is returned. + */ + getImageProperty(key:string, options: GetImagePropertyOptions, callback: AsyncCallback): void; + + /** + * Releases an ImageSource instance and uses a callback to return the result. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param callback Callback to return the operation result. + */ + release(callback: AsyncCallback): void; + + /** + * Releases an ImageSource instance and uses a promise to return the result. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @return A Promise instance used to return the operation result. + */ + release(): Promise; + + /** + * Supported image formats. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + */ + readonly supportedFormats: Array; + } + + interface ImagePacker { + /** + * Compresses or packs an image and uses a callback to return the result. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param source Image to be processed. + * @param option Option for image packing. + * @param callback Callback used to return the packed data. + */ + packing(source: ImageSource, option: PackingOption, callback: AsyncCallback): void; + + /** + * Compresses or packs an image and uses a promise to return the result. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param source Image to be processed. + * @param option Option for image packing. + * @return A Promise instance used to return the compressed or packed data. + */ + packing(source: ImageSource, option: PackingOption): Promise; + + /** + * Compresses or packs a pixelmap. + * @param source PixelMap to be processed. + * @param option Option for image packing. + * @return Compressed or packed data. + * @since 8 + */ + packing(source: PixelMap, option: PackingOption, callback: AsyncCallback): void; + packing(source: PixelMap, option: PackingOption): Promise; + + /** + * Releases an ImagePacker instance and uses a callback to return the result. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @param callback Callback to return the operation result. + */ + release(callback: AsyncCallback): void; + + /** + * Releases an ImagePacker instance and uses a promise to return the result. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + * @return A Promise instance used to return the operation result. + */ + release(): Promise; + + /** + * Supported image formats. + * @since 6 + * @SysCap SystemCapability.Multimedia.Image + * @devices phone, tablet, tv, wearable, car + * @import import image from '@ohos.multimedia.image' + */ + readonly supportedFormats: Array; + } +} + export default image; \ No newline at end of file diff --git a/interfaces/kits/js/common/include/image_packer_napi.h b/interfaces/kits/js/common/include/image_packer_napi.h new file mode 100644 index 0000000000000000000000000000000000000000..8d6b5f694b7729b9bdca3e6f893304caa0496f08 --- /dev/null +++ b/interfaces/kits/js/common/include/image_packer_napi.h @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef IMAGE_PACKER_NAPI_H_ +#define IMAGE_PACKER_NAPI_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "image_packer.h" +#include "image_type.h" +#include "image_source.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "pixel_map.h" +#include "image_source_napi.h" + +namespace OHOS { +namespace Media { +class ImagePackerNapi { +public: + ImagePackerNapi(); + ~ImagePackerNapi(); + static napi_value Init(napi_env env, napi_value exports); + static napi_value CreateImagePacker(napi_env env, napi_callback_info info); + +private: + static napi_value Constructor(napi_env env, napi_callback_info info); + static void Destructor(napi_env env, void *nativeObject, void *finalize); + static napi_value Packing(napi_env env, napi_callback_info info); + static napi_value Release(napi_env env, napi_callback_info info); + + static napi_ref sConstructor_; + static std::shared_ptr sImgSource_; + static std::shared_ptr sImgPck_; + + napi_env env_ = nullptr; + napi_ref wrapper_ = nullptr; + std::shared_ptr nativeImgPck = nullptr; +}; +} // namespace Media +} // namespace OHOS +#endif /* IMAGE_PACKER_NAPI_H_ */ diff --git a/interfaces/kits/js/common/include/image_source_napi.h b/interfaces/kits/js/common/include/image_source_napi.h index 8f522dad4a969a3f8be7f2e6209a989d6ed7ec07..b2125c11ebede1f9403c988170eb145ebf315997 100644 --- a/interfaces/kits/js/common/include/image_source_napi.h +++ b/interfaces/kits/js/common/include/image_source_napi.h @@ -21,6 +21,7 @@ #include "image_source.h" #include "napi/native_api.h" #include "napi/native_node_api.h" +#include "pixel_map_napi.h" namespace OHOS { namespace Media { @@ -30,7 +31,7 @@ public: ~ImageSourceNapi(); static napi_value Init(napi_env env, napi_value exports); - + std::shared_ptr nativeImgSrc = nullptr; private: static napi_value Constructor(napi_env env, napi_callback_info info); static void Destructor(napi_env env, void *nativeObject, void *finalize); @@ -42,6 +43,7 @@ private: static napi_value CreateImageSource(napi_env env, napi_callback_info info); static napi_value CreateIncrementalSource(napi_env env, napi_callback_info info); + static napi_value CreateImageSourceComplete(napi_env env, napi_status status, void *data); // methods static napi_value GetImageInfo(napi_env env, napi_callback_info info); static napi_value CreatePixelMap(napi_env env, napi_callback_info info); @@ -55,7 +57,7 @@ private: napi_env env_ = nullptr; napi_ref wrapper_ = nullptr; - std::shared_ptr nativeImgSrc = nullptr; + bool isRelease = false; }; } // namespace Media diff --git a/interfaces/kits/js/common/include/native_module_ohos_image.h b/interfaces/kits/js/common/include/native_module_ohos_image.h index a7370598fc5f698f37f9068db6405a3ade380d4f..b3670f97699a3d21f0da46771676b08e4f604522 100644 --- a/interfaces/kits/js/common/include/native_module_ohos_image.h +++ b/interfaces/kits/js/common/include/native_module_ohos_image.h @@ -19,5 +19,6 @@ #include "napi/native_node_api.h" #include "image_source_napi.h" #include "pixel_map_napi.h" +#include "image_packer_napi.h" #endif /* NATIVE_MODULE_OHOS_IMAGE_H_ */ diff --git a/ohos.build b/ohos.build index 1e632475230fa55e38c95489243bbbe70164d69c..e90e03818ef8cae8b3ad90de0081c932b30782d0 100755 --- a/ohos.build +++ b/ohos.build @@ -27,7 +27,7 @@ ], "header_base": "//foundation/multimedia/image_standard/interfaces/innerkits/include" }, - "name": "//foundation/multimedia/image_standard/interfaces/innerkits:image" + "name": "//foundation/multimedia/image_standard/interfaces/innerkits:image_native" } ], diff --git a/plugins/common/libs/image/libjpegplugin/include/jpeg_decoder.h b/plugins/common/libs/image/libjpegplugin/include/jpeg_decoder.h index 9e5c2dc3ccbb8bff234154b62508a6327d643a6f..588f4ecafd01874f8c0b114e6358846141e43938 100644 --- a/plugins/common/libs/image/libjpegplugin/include/jpeg_decoder.h +++ b/plugins/common/libs/image/libjpegplugin/include/jpeg_decoder.h @@ -50,9 +50,11 @@ public: uint32_t Decode(uint32_t index, DecodeContext &context) override; uint32_t GetImageSize(uint32_t index, PlSize &size) override; uint32_t PromoteIncrementalDecode(uint32_t index, ProgDecodeContext &context) override; - + uint32_t GetImagePropertyInt(uint32_t index, const std::string &key, int32_t &value) override; + uint32_t GetImagePropertyString(uint32_t index, const std::string &key, std::string &value) override; private: DISALLOW_COPY_AND_MOVE(JpegDecoder); + int ExifPrintMethod(); J_COLOR_SPACE GetDecodeFormat(PlPixelFormat format, PlPixelFormat &outputFormat); void CreateHwDecompressor(); uint32_t DoSwDecode(DecodeContext &context); diff --git a/plugins/common/libs/image/libjpegplugin/include/jpeg_utils.h b/plugins/common/libs/image/libjpegplugin/include/jpeg_utils.h index 51ac52fe0aabb7ae3eef959e434b9e4f520f33aa..9896a3c32f88432346070bf0bdfb4b3947ae862a 100644 --- a/plugins/common/libs/image/libjpegplugin/include/jpeg_utils.h +++ b/plugins/common/libs/image/libjpegplugin/include/jpeg_utils.h @@ -19,6 +19,7 @@ #include #include #include +#include #include "hilog/log.h" #include "input_data_stream.h" #include "jerror.h" @@ -32,6 +33,7 @@ static constexpr uint8_t SET_JUMP_VALUE = 1; static constexpr uint8_t RW_LINE_NUM = 1; static constexpr uint16_t JPEG_BUFFER_SIZE = 1024; static constexpr uint32_t JPEG_IMAGE_NUM = 1; +static constexpr uint32_t PRINTF_SUCCESS = 0; // redefine jpeg error manager struct. struct ErrorMgr : jpeg_error_mgr { @@ -74,6 +76,7 @@ void TermSrcStream(j_decompress_ptr dinfo); void InitDstStream(j_compress_ptr cinfo); boolean EmptyOutputBuffer(j_compress_ptr cinfo); void TermDstStream(j_compress_ptr cinfo); +std::string DoubleToString(double num); } // namespace ImagePlugin } // namespace OHOS diff --git a/plugins/common/libs/image/libjpegplugin/src/jpeg_decoder.cpp b/plugins/common/libs/image/libjpegplugin/src/jpeg_decoder.cpp index 2989f29a1ed1e3e5723964a109b87cac6ba11422..977f8d20b2bff5f93fc270354ed5c1c9954b4d07 100644 --- a/plugins/common/libs/image/libjpegplugin/src/jpeg_decoder.cpp +++ b/plugins/common/libs/image/libjpegplugin/src/jpeg_decoder.cpp @@ -29,6 +29,7 @@ using namespace MultimediaPlugin; using namespace Media; static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_TAG_DOMAIN_ID_PLUGIN, "JpegDecoder" }; namespace { +constexpr uint32_t NUM_100 = 100; constexpr uint32_t PIXEL_BYTES_RGB_565 = 2; constexpr uint32_t MARKER_SIZE = 2; constexpr uint32_t MARKER_LENGTH = 2; @@ -46,6 +47,14 @@ constexpr uint8_t JPG_MARKER_RSTN = 0XD7; constexpr uint8_t JPG_MARKER_APP = 0XE0; constexpr uint8_t JPG_MARKER_APP0 = 0XE0; constexpr uint8_t JPG_MARKER_APPN = 0XEF; +const std::string BITS_PER_SAMPLE = "BitsPerSample"; +const std::string ORIENTATION = "Orientation"; +const std::string IMAGE_HEIGHT = "ImageHeight"; +const std::string IMAGE_WIDTH = "ImageWidth"; +const std::string GPS_LATITUDE = "GPSLatitude"; +const std::string GPS_LONGITUDE = "GPSLongitude"; +const std::string GPS_LATITUDE_REF = "GPSLatitudeRef"; +const std::string GPS_LONGITUDE_REF = "GPSLongitudeRef"; } // namespace PluginServer &JpegDecoder::pluginServer_ = DelayedRefSingleton::GetInstance(); @@ -361,7 +370,7 @@ uint32_t JpegDecoder::PromoteIncrementalDecode(uint32_t index, ProgDecodeContext } // get promote decode progress, in percentage: 0~100. progContext.totalProcessProgress = - decodeInfo_.output_height == 0 ? 0 : decodeInfo_.output_scanline * 100 / decodeInfo_.output_height; + decodeInfo_.output_height == 0 ? 0 : (decodeInfo_.output_scanline * NUM_100) / decodeInfo_.output_height; HiLog::Debug(LABEL, "incremental decode progress %{public}u.", progContext.totalProcessProgress); return ret; } @@ -529,5 +538,18 @@ uint32_t JpegDecoder::StartDecompress(const PixelDecodeOptions &opts) streamPosition_ = srcMgr_.inputStream->Tell(); return Media::SUCCESS; } + +uint32_t JpegDecoder::GetImagePropertyInt(uint32_t index, const std::string &key, int32_t &value) +{ + HiLog::Error(LABEL, "[GetImagePropertyInt] enter jped plugin, key:%{public}s", key.c_str()); + return Media::SUCCESS; +} + +uint32_t JpegDecoder::GetImagePropertyString(uint32_t index, const std::string &key, std::string &value) +{ + HiLog::Error(LABEL, "[GetImagePropertyString] enter jped plugin, key:%{public}s", key.c_str()); + + return Media::SUCCESS; +} } // namespace ImagePlugin } // namespace OHOS diff --git a/plugins/common/libs/image/libjpegplugin/src/jpeg_utils.cpp b/plugins/common/libs/image/libjpegplugin/src/jpeg_utils.cpp index 36aeff58125d37a97ff104f0266a6e175a985cb4..f4e8a4106b820329c27464885e24a56a73e400ab 100644 --- a/plugins/common/libs/image/libjpegplugin/src/jpeg_utils.cpp +++ b/plugins/common/libs/image/libjpegplugin/src/jpeg_utils.cpp @@ -14,6 +14,7 @@ */ #include "jpeg_utils.h" +#include "securec.h" namespace OHOS { namespace ImagePlugin { @@ -190,5 +191,15 @@ void TermDstStream(j_compress_ptr cinfo) } dest->outputStream->Flush(); } +std::string DoubleToString(double num) +{ + char str[256]; + int32_t ret = sprintf_s(str, sizeof(str), "%lf", num); + if (ret <= PRINTF_SUCCESS) { + return ""; + } + std::string result = str; + return result; +} } // namespace ImagePlugin } // namespace OHOS diff --git a/test/resource/image/images/moving_test.gif b/test/resource/image/images/moving_test.gif index 6643f465ae71b561e337349063f9fa13500ad4bf..0d3d41c0c832596b26700070d4bc06dec87269b2 100755 Binary files a/test/resource/image/images/moving_test.gif and b/test/resource/image/images/moving_test.gif differ diff --git a/test/resource/image/images/test.gif b/test/resource/image/images/test.gif index dfd33b993d159549a1900684e18be89605eab8ad..002c835575821159c38d3f64397b3cf837c3e5f1 100755 Binary files a/test/resource/image/images/test.gif and b/test/resource/image/images/test.gif differ diff --git a/test/resource/image/ohos_test.xml b/test/resource/image/ohos_test.xml index 9834418d1af85b5b33f55d355b0b83d5eb49b2f8..7054417622d204ed5703006234e8e047c860cf65 100644 --- a/test/resource/image/ohos_test.xml +++ b/test/resource/image/ohos_test.xml @@ -16,56 +16,56 @@ - - -