[
  {
    "path": ".github/workflows/android.yml",
    "content": "name: Android CI\n\non:\n  push:\n    branches: [ \"master\", \"main\" ]\n  pull_request:\n    branches: [ \"master\", \"main\" ]\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n\n    steps:\n    - name: Checkout code\n      uses: actions/checkout@v4\n    \n    - name: Set up JDK 17\n      uses: actions/setup-java@v4\n      with:\n        java-version: '17'\n        distribution: 'temurin'\n        cache: gradle\n\n    - name: Set up Android SDK\n      uses: android-actions/setup-android@v3\n\n    - name: Grant execute permission for gradlew\n      run: chmod +x gradlew\n\n    - name: Build with Gradle\n      run: ./gradlew build\n\n    - name: Run Unit Tests\n      run: ./gradlew test\n"
  },
  {
    "path": ".gitignore",
    "content": "*.iml\n.gradle\n/local.properties\n/.idea/caches\n/.idea/libraries\n/.idea/modules.xml\n/.idea/workspace.xml\n/.idea/navEditor.xml\n/.idea/assetWizardSettings.xml\n.DS_Store\n/build\n/captures\n.externalNativeBuild\n.cxx\nlocal.properties\n.idea/\ndocs/\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   Copyright 2026 郑梓斌\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# Luban 2\n\n[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)\n[![Maven Central](https://img.shields.io/maven-central/v/top.zibin/luban.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:top.zibin%20a:luban)\n[![API](https://img.shields.io/badge/API-21%2B-brightgreen.svg?style=flat)](https://android-arsenal.com/api?level=21)\n\n[中文](README.md) | [English](README_EN.md)\n\nLuban 2（鲁班 2） —— 高效简洁的 Android 图片压缩工具库，像素级还原微信朋友圈压缩策略。\n\n## 📑 目录\n\n- [📖 项目描述](#-项目描述)\n- [📊 效果与对比](#-效果与对比)\n  - [🔬 核心算法特性](#-核心算法特性)\n- [📦 导入](#-导入)\n- [💻 使用](#-使用)\n  - [⚡ Kotlin (Coroutines)](#-kotlin-coroutines)\n  - [☕ Java / Builder 模式](#-java--builder-模式)\n- [☕ 捐助](#-捐助)\n- [📄 License](#-license)\n\n# 📖 项目描述\n\n目前做`App`开发总绕不开图片这个元素。但是随着手机拍照分辨率的提升，图片的压缩成为一个很重要的问题。单纯对图片进行裁切，压缩已经有很多文章介绍。但是裁切成多少，压缩成多少却很难控制好，裁切过头图片太小，质量压缩过头则显示效果太差。\n\n于是自然想到`App`巨头\"微信\"会是怎么处理，`Luban`（鲁班）就是通过在微信朋友圈发送近100张不同分辨率图片，对比原图与微信压缩后的图片逆向推算出来的压缩算法。\n\n因为是逆向推算，效果还没法跟微信一模一样，但是已经很接近微信朋友圈压缩后的效果，具体看以下对比！\n\n本库是 `Luban` 的 **Kotlin 重构版本**，在升级核心算法的同时，利用 **Kotlin Coroutines** 和 **TurboJPEG** 进行了深度优化。新算法比原算法更加健壮和高效，提供更高效的异步处理和更优质的压缩效果。\n\n# 📊 效果与对比\n\n| 图片类型 | 原图（分辨率, 大小） | Luban（分辨率, 大小） | Wechat（分辨率, 大小） |\n| :--- | :--- | :--- | :--- |\n| **标准拍照** | 3024×4032, 5.10MB | 1440×1920, 305KB | 1440×1920, 303KB |\n| **高清大图** | 4000×6000, 12.10MB | 1440×2160, 318KB | 1440×2160, 305KB |\n| **2K 截图** | 1440×3200, 2.10MB | 1440×3200, 148KB | 1440×3200, 256KB |\n| **超长记录** | 1242×22080, 6.10MB | 758×13490, 290KB | 744×13129, 256KB |\n| **全景横图** | 12000×5000, 8.10MB | 1440×600, 126KB | 1440×600, 123KB |\n| **设计原稿** | 6000×6000, 6.90MB | 1440×1440, 263KB | 1440×1440, 279KB |\n\n## 🔬 核心算法特性\n\n本库采用**自适应统一图像压缩算法 (Adaptive Unified Image Compression)**，通过原图的分辨率特征，动态应用差异化策略，实现画质与体积的最优平衡。\n\n### 智能分辨率决策\n\n- **高清基准 (1440p)**：默认以 1440px 作为短边基准，确保在现代 2K/4K 屏幕上的视觉清晰度\n- **全景墙策略**：自动识别超大全景图（长边 >10800px），锁定长边为 1440px，保留完整视野\n- **超大像素陷阱**：对超过 4096万像素的超高像素图自动执行 1/4 降采样处理\n- **长图内存保护**：针对超长截图建立 10.24MP 像素上限，通过等比缩放防止 OOM\n\n### 自适应比特率控制\n\n- **极小图 (<0.5MP)**：几乎不进行有损压缩，防止压缩伪影\n- **高频信息图 (0.5-1MP)**：提高编码质量，补偿分辨率损失\n- **标准图片 (1-3MP)**：应用平衡系数，对标主流社交软件体验\n- **超大图/长图 (>3MP)**：应用高压缩率，显著减少体积\n\n### 健壮性保障\n\n- **膨胀回退**：压缩后体积大于原图时，自动透传原图，确保绝不\"负优化\"\n- **智能格式透传**：保留小体积 PNG 的透明通道，大体积 PNG 自动转码为 JPEG\n- **输入防御**：妥善处理极端分辨率输入（0、负数、1px 等），防止崩溃\n\n# 📦 导入\n\n确保项目的 `build.gradle` 或 `build.gradle.kts` 已配置 Maven Central 仓库：\n\n```kotlin\nrepositories {\n    mavenCentral()\n}\n```\n\n在模块的构建文件中添加依赖：\n\n**Kotlin DSL (`build.gradle.kts`):**\n\n```kotlin\ndependencies {\n    implementation(\"top.zibin:luban:2.0.1\")\n}\n```\n\n**Groovy (`build.gradle`):**\n\n```groovy\ndependencies {\n    implementation 'top.zibin:luban:2.0.1'\n}\n```\n\n> 注意：请访问 [Maven Central](https://search.maven.org/search?q=g:top.zibin%20a:luban) 查看最新版本号。\n\n# 💻 使用\n\n### ⚡ Kotlin (Coroutines)\n\nLuban 提供了三种 Kotlin 调用方式，从最符合 Kotlin 习惯到传统方式：\n\n#### 1. DSL 风格（推荐）\n\n最符合 Kotlin 习惯的方式是使用 DSL API：\n\n```kotlin\nlifecycleScope.launch {\n    val results = luban(context) {\n        outputDir = File(context.cacheDir, \"compressed\")\n        \n        compress(imageUri1)\n        compress(imageUri2)\n        compress(imageFile1)\n        compress(listOf(imageFile2, imageFile3))\n        compress(listOf(imageUri3, imageUri4))\n    }\n    \n    results.forEach { result ->\n        result.getOrNull()?.let { file ->\n            Log.d(\"Luban\", \"压缩成功: ${file.absolutePath}\")\n        } ?: run {\n            val error = result.exceptionOrNull()\n            Log.e(\"Luban\", \"压缩失败: ${error?.message}\")\n        }\n    }\n}\n```\n\n**注意：** \n- 对于 `Uri` 类型的压缩，如果不指定 `outputDir`，默认使用 `context.cacheDir`。对于 `File` 类型的压缩，必须显式设置 `outputDir`。\n- DSL 配置是声明式的，配置顺序不影响结果。你可以先设置 `outputDir` 再调用 `compress()`，也可以先调用 `compress()` 再设置 `outputDir`。\n\n#### 2. 扩展函数\n\n你也可以使用扩展函数，获得更流畅的 API：\n\n```kotlin\nlifecycleScope.launch {\n    val result = imageUri.compressTo(context)\n    \n    result.getOrElse { error ->\n        Log.e(\"Luban\", \"压缩失败: ${error.message}\")\n        return@launch\n    }.let { file ->\n        Log.d(\"Luban\", \"压缩成功: ${file.absolutePath}\")\n    }\n}\n```\n\n**压缩单个文件：**\n```kotlin\nval result = inputFile.compressTo(outputDir)\n```\n\n**压缩到指定文件：**\n```kotlin\nval result = inputFile.compressToFile(outputFile)\n```\n\n**批量压缩：**\n```kotlin\nval results = fileList.compressTo(outputDir)\nval results = uriList.compressTo(context)\n```\n\n#### 3. 传统静态方法\n\n使用传统静态方法：\n\n```kotlin\nlifecycleScope.launch {\n    val result = Luban.compress(context, inputUri, outputDir)\n    \n    result.getOrElse { error ->\n        Log.e(\"Luban\", \"压缩失败: ${error.message}\")\n        return@launch\n    }.let { file ->\n        Log.d(\"Luban\", \"压缩成功: ${file.absolutePath}\")\n    }\n}\n```\n\n**可用方法：**\n- `Luban.compress(context, input: Uri, outputDir: File = context.cacheDir): Result<File>`\n- `Luban.compress(input: File, outputDir: File): Result<File>`\n- `Luban.compressToFile(input: File, output: File): Result<File>`\n- `Luban.compress(context, inputs: List<Uri>, outputDir: File = context.cacheDir): List<Result<File>>`\n- `Luban.compress(inputs: List<File>, outputDir: File): List<Result<File>>`\n\n**在其他协程作用域中使用：**\n```kotlin\nval scope = CoroutineScope(Dispatchers.Main + SupervisorJob())\n\nscope.launch {\n    val result = Luban.compress(context, inputUri)\n    \n    result.getOrElse { error ->\n        // 处理错误\n        return@launch\n    }.let { file ->\n        // 处理成功\n    }\n}\n```\n\n### ☕ Java / Builder 模式\n\n对于 Java 项目或偏好回调风格的开发者，可以使用兼容旧版风格的 `Luban.with()` API。\n\n#### 压缩单张图片\n\n```java\nLuban.with(context)\n    .load(imageFile) // 支持 File, Uri, 或 String 路径\n    .setTargetDir(context.getCacheDir())\n    .bindLifecycle(lifecycleOwner) // 可选：页面销毁时自动取消\n    .setCompressListener(new OnCompressListener() {\n        @Override\n        public void onStart() {\n            // 开始压缩\n        }\n\n        @Override\n        public void onSuccess(File file) {\n            // 压缩成功\n        }\n\n        @Override\n        public void onError(Throwable e) {\n            // 发生错误\n        }\n    })\n    .launch();\n```\n\n#### 压缩多张图片\n\n```java\nList<String> imagePaths = ...; // 图片路径列表\n\nLuban.with(context)\n    .load(imagePaths) // 加载图片列表\n    .setTargetDir(context.getCacheDir())\n    .setCompressListener(new OnCompressListener() {\n        @Override\n        public void onStart() {\n            // 开始压缩\n        }\n\n        @Override\n        public void onSuccess(File file) {\n            // 每张图片压缩成功后都会回调一次\n            Log.d(\"Luban\", \"Compressed: \" + file.getAbsolutePath());\n        }\n\n        @Override\n        public void onError(Throwable e) {\n            // 发生错误\n        }\n    })\n    .launch();\n```\n\n# ☕ 捐助\n\n如果这个项目对您有帮助，欢迎通过以下方式支持我的工作。您的支持是我持续改进和维护这个项目的动力。\n\n<div align=\"center\">\n\n<table>\n<tr>\n<td align=\"center\">\n<img src=\"images/alipay.png\" width=\"300\" alt=\"支付宝收款码\" />\n</td>\n<td width=\"50\"></td>\n<td align=\"center\">\n<img src=\"images/wechat.png\" width=\"300\" alt=\"微信收款码\" />\n</td>\n</tr>\n</table>\n\n</div>\n\n感谢您的支持！🙏\n\n# 📄 License\n\n    Copyright 2025 郑梓斌\n    \n    Licensed under the Apache License, Version 2.0 (the \"License\");\n    you may not use this file except in compliance with the License.\n    You may obtain a copy of the License at\n    \n        http://www.apache.org/licenses/LICENSE-2.0\n    \n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n"
  },
  {
    "path": "README_EN.md",
    "content": "# Luban 2\n\n[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)\n[![Maven Central](https://img.shields.io/maven-central/v/top.zibin/luban.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:top.zibin%20a:luban)\n[![API](https://img.shields.io/badge/API-21%2B-brightgreen.svg?style=flat)](https://android-arsenal.com/api?level=21)\n\n[English](README_EN.md) | [中文](README.md)\n\nLuban 2 — An efficient and concise Android image compression library that closely replicates the compression strategy of WeChat Moments.\n\n## 📑 Table of Contents\n\n- [📖 Project Description](#-project-description)\n- [📊 Effects & Comparison](#-effects--comparison)\n  - [🔬 Core Algorithm Features](#-core-algorithm-features)\n- [📦 Import](#-import)\n- [💻 Usage](#-usage)\n  - [⚡ Kotlin (Coroutines)](#-kotlin-coroutines)\n  - [☕ Java / Builder Pattern](#-java--builder-pattern)\n- [☕ Donation](#-donation)\n- [📄 License](#-license)\n\n# 📖 Project Description\n\nImages are an essential part of app development. With the increasing resolution of mobile cameras, image compression has become a critical issue. While there are many articles on simple cropping and compression, choosing the right crop and compression levels is tricky—cropping too much results in tiny images, while over-compressing leads to poor display quality.\n\nNaturally, one wonders how the industry giant \"WeChat\" handles this. `Luban` was derived by reverse-engineering WeChat Moments’ behavior: we sent nearly 100 images with different resolutions and compared the originals with WeChat’s outputs to infer the compression strategy.\n\nSince this behavior is inferred from observation, the results may not match WeChat exactly, but they are very close. See the comparison below!\n\nThis library is the **Kotlin refactored version** of `Luban`. While upgrading the core algorithm, it is optimized with **Kotlin Coroutines** and **TurboJPEG** for faster processing and better output quality. The new algorithm is more robust and efficient than the original, providing more efficient asynchronous processing and superior compression quality.\n\n# 📊 Effects & Comparison\n\n| Image Type | Original | Luban | WeChat |\n| :--- | :--- | :--- | :--- |\n| **Standard Photo** | 3024×4032, 5.10MB | 1440×1920, 305KB | 1440×1920, 303KB |\n| **High-Res Photo** | 4000×6000, 12.10MB | 1440×2160, 318KB | 1440×2160, 305KB |\n| **2K Screenshot** | 1440×3200, 2.10MB | 1440×3200, 148KB | 1440×3200, 256KB |\n| **Long Screenshot** | 1242×22080, 6.10MB | 758×13490, 290KB | 744×13129, 256KB |\n| **Panorama** | 12000×5000, 8.10MB | 1440×600, 126KB | 1440×600, 123KB |\n| **Design Draft** | 6000×6000, 6.90MB | 1440×1440, 263KB | 1440×1440, 279KB |\n\n## 🔬 Core Algorithm Features\n\nThis library uses an **Adaptive Unified Image Compression** algorithm that dynamically applies differentiated strategies based on the original image's resolution characteristics to achieve optimal balance between quality and file size.\n\n### Intelligent Resolution Decision\n\n- **High-Definition Baseline (1440p)**: Uses 1440px as the default short-side baseline, ensuring visual clarity on modern 2K/4K displays\n- **Panorama Wall Strategy**: Automatically identifies ultra-wide panoramas (long side >10800px), locks the long side to 1440px while preserving the full field of view\n- **Mega-Pixel Trap**: Automatically applies 1/4 downsampling to images exceeding 41 megapixels (≈40.96 MP)\n- **Long Image Memory Protection**: Establishes a 10.24MP pixel cap for ultra-long screenshots, reducing the risk of out-of-memory (OOM) errors through proportional scaling\n\n### Adaptive Bitrate Control\n\n- **Tiny Images (<0.5MP)**: Minimal lossy compression to prevent compression artifacts\n- **High-Frequency Images (0.5-1MP)**: Enhanced encoding quality to compensate for resolution loss\n- **Standard Images (1-3MP)**: Balanced coefficients matching mainstream social media apps\n- **Large/Long Images (>3MP)**: High compression ratios to significantly reduce file size\n\n### Robustness Guarantees\n\n- **Inflation Fallback**: Automatically returns the original image if compressed size exceeds original, avoiding making files larger after compression\n- **Smart Format Passthrough**: Preserves transparency for small PNG files, and converts large PNG files to JPEG when appropriate\n- **Input Defense**: Safely handles extreme resolution inputs (0, negative, 1px, etc.), preventing crashes\n\n# 📦 Import\n\nMake sure `mavenCentral()` is included in your repositories.\n\nAdd the dependency to your module's `build.gradle.kts` file:\n\n```kotlin\ndependencies {\n    implementation(\"top.zibin:luban:2.0.1\")\n}\n```\n\n# 💻 Usage\n\n### ⚡ Kotlin (Coroutines)\n\nLuban provides three ways to use the library in Kotlin, from most idiomatic to traditional:\n\n#### 1. DSL Style (Recommended)\n\nThe most Kotlin-idiomatic way is using the DSL API:\n\n```kotlin\nlifecycleScope.launch {\n    val results = luban(context) {\n        outputDir = File(context.cacheDir, \"compressed\")\n        \n        compress(imageUri1)\n        compress(imageUri2)\n        compress(imageFile1)\n        compress(listOf(imageFile2, imageFile3))\n        compress(listOf(imageUri3, imageUri4))\n    }\n    \n    results.forEach { result ->\n        result.getOrNull()?.let { file ->\n            Log.d(\"Luban\", \"Compressed: ${file.absolutePath}\")\n        } ?: run {\n            val error = result.exceptionOrNull()\n            Log.e(\"Luban\", \"Error: ${error?.message}\")\n        }\n    }\n}\n```\n\n**Note:** \n- For `Uri` compression, if `outputDir` is not specified, it defaults to `context.cacheDir`. For `File` compression, `outputDir` must be explicitly set.\n- The DSL configuration is declarative, so the order of configuration does not affect the result. You can set `outputDir` before calling `compress()`, or call `compress()` before setting `outputDir`.\n\n#### 2. Extension Functions\n\nYou can also use extension functions for a more fluent API:\n\n```kotlin\nlifecycleScope.launch {\n    val result = imageUri.compressTo(context)\n    \n    result.getOrElse { error ->\n        Log.e(\"Luban\", \"Error: ${error.message}\")\n        return@launch\n    }.let { file ->\n        Log.d(\"Luban\", \"Compressed: ${file.absolutePath}\")\n    }\n}\n```\n\n**Compress a single file:**\n```kotlin\nval result = inputFile.compressTo(outputDir)\n```\n\n**Compress to a specific output file:**\n```kotlin\nval result = inputFile.compressToFile(outputFile)\n```\n\n**Compress multiple files:**\n```kotlin\nval results = fileList.compressTo(outputDir)\nval results = uriList.compressTo(context)\n```\n\n#### 3. Traditional Static Methods\n\nThe traditional way using static methods:\n\n```kotlin\nlifecycleScope.launch {\n    val result = Luban.compress(context, inputUri, outputDir)\n    \n    result.getOrElse { error ->\n        Log.e(\"Luban\", \"Error: ${error.message}\")\n        return@launch\n    }.let { file ->\n        Log.d(\"Luban\", \"Compressed: ${file.absolutePath}\")\n    }\n}\n```\n\n**Available methods:**\n- `Luban.compress(context, input: Uri, outputDir: File = context.cacheDir): Result<File>`\n- `Luban.compress(input: File, outputDir: File): Result<File>`\n- `Luban.compressToFile(input: File, output: File): Result<File>`\n- `Luban.compress(context, inputs: List<Uri>, outputDir: File = context.cacheDir): List<Result<File>>`\n- `Luban.compress(inputs: List<File>, outputDir: File): List<Result<File>>`\n\n**Use in a custom CoroutineScope:**\n```kotlin\nval scope = CoroutineScope(Dispatchers.Main + SupervisorJob())\n\nscope.launch {\n    val result = Luban.compress(context, inputUri)\n    \n    result.getOrElse { error ->\n        // Handle error\n        return@launch\n    }.let { file ->\n        // Handle success\n    }\n}\n```\n\n### ☕ Java / Builder Pattern\n\nFor Java projects or if you prefer a callback-based approach, use the `Luban.with()` API which is compatible with the original library style.\n\n#### Compress a Single File\n\n```java\nLuban.with(context)\n    .load(imageFile) // Can be File, Uri, or String path\n    .setTargetDir(context.getCacheDir())\n    .bindLifecycle(lifecycleOwner) // Optional: Auto-cancel on destroy\n    .setCompressListener(new OnCompressListener() {\n        @Override\n        public void onStart() {\n            // Compression started\n        }\n\n        @Override\n        public void onSuccess(File file) {\n            // Compression finished successfully\n        }\n\n        @Override\n        public void onError(Throwable e) {\n            // An error occurred\n        }\n    })\n    .launch();\n```\n\n#### Compress Multiple Files\n\n```java\nList<String> imagePaths = ...; // List of image paths\n\nLuban.with(context)\n    .load(imagePaths) // Load a list of images\n    .setTargetDir(context.getCacheDir())\n    .setCompressListener(new OnCompressListener() {\n        @Override\n        public void onStart() {\n            // Compression started\n        }\n\n        @Override\n        public void onSuccess(File file) {\n            // Called for EACH successfully compressed image\n            Log.d(\"Luban\", \"Compressed: \" + file.getAbsolutePath());\n        }\n\n        @Override\n        public void onError(Throwable e) {\n            // An error occurred\n        }\n    })\n    .launch();\n```\n\n# ☕ Donation\n\nIf this project has been helpful to you, please consider supporting my work through the following methods. Your support is the motivation for me to continue improving and maintaining this project.\n\n<div align=\"center\">\n\n<table>\n<tr>\n<td align=\"center\">\n<img src=\"images/alipay.png\" width=\"300\" alt=\"Alipay QR Code\" />\n</td>\n<td width=\"50\"></td>\n<td align=\"center\">\n<img src=\"images/wechat.png\" width=\"300\" alt=\"WeChat QR Code\" />\n</td>\n</tr>\n</table>\n\n</div>\n\nThank you for your support! 🙏\n\n# 📄 License\n\n    Copyright 2025 Zibin\n    \n    Licensed under the Apache License, Version 2.0 (the \"License\");\n    you may not use this file except in compliance with the License.\n    You may obtain a copy of the License at\n    \n        http://www.apache.org/licenses/LICENSE-2.0\n    \n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n"
  },
  {
    "path": "app/.gitignore",
    "content": "/build"
  },
  {
    "path": "app/build.gradle.kts",
    "content": "plugins {\n    alias(libs.plugins.android.application)\n    alias(libs.plugins.kotlin.android)\n    alias(libs.plugins.kotlin.compose)\n}\n\nandroid {\n    namespace = \"top.zibin.luban.app\"\n    compileSdk {\n        version = release(36)\n    }\n\n    defaultConfig {\n        applicationId = \"top.zibin.luban.app\"\n        minSdk = 26\n        targetSdk = 36\n        versionCode = 1\n        versionName = \"1.0\"\n\n        testInstrumentationRunner = \"androidx.test.runner.AndroidJUnitRunner\"\n    }\n\n    buildTypes {\n        release {\n            isMinifyEnabled = false\n            proguardFiles(\n                getDefaultProguardFile(\"proguard-android-optimize.txt\"),\n                \"proguard-rules.pro\"\n            )\n        }\n    }\n    compileOptions {\n        sourceCompatibility = JavaVersion.VERSION_17\n        targetCompatibility = JavaVersion.VERSION_17\n    }\n    buildFeatures {\n        compose = true\n    }\n}\n\ndependencies {\n    implementation(project(\":luban\"))\n    implementation(libs.androidx.core.ktx)\n    implementation(libs.androidx.lifecycle.runtime.ktx)\n    implementation(libs.androidx.activity.compose)\n    implementation(platform(libs.androidx.compose.bom))\n    implementation(libs.androidx.compose.ui)\n    implementation(libs.androidx.compose.ui.graphics)\n    implementation(libs.androidx.compose.ui.tooling.preview)\n    implementation(libs.androidx.compose.material3)\n    implementation(libs.androidx.compose.material.icons.extended)\n    implementation(libs.coil.compose)\n    testImplementation(libs.junit)\n    androidTestImplementation(libs.androidx.junit)\n    androidTestImplementation(libs.androidx.espresso.core)\n    androidTestImplementation(platform(libs.androidx.compose.bom))\n    androidTestImplementation(libs.androidx.compose.ui.test.junit4)\n    debugImplementation(libs.androidx.compose.ui.tooling)\n    debugImplementation(libs.androidx.compose.ui.test.manifest)\n}"
  },
  {
    "path": "app/proguard-rules.pro",
    "content": "# Add project specific ProGuard rules here.\n# You can control the set of applied configuration files using the\n# proguardFiles setting in build.gradle.\n#\n# For more details, see\n#   http://developer.android.com/guide/developing/tools/proguard.html\n\n# If your project uses WebView with JS, uncomment the following\n# and specify the fully qualified class name to the JavaScript interface\n# class:\n#-keepclassmembers class fqcn.of.javascript.interface.for.webview {\n#   public *;\n#}\n\n# Uncomment this to preserve the line number information for\n# debugging stack traces.\n#-keepattributes SourceFile,LineNumberTable\n\n# If you keep the line number information, uncomment this to\n# hide the original source file name.\n#-renamesourcefileattribute SourceFile"
  },
  {
    "path": "app/src/androidTest/java/top/zibin/luban/app/ExampleInstrumentedTest.kt",
    "content": "package top.zibin.luban.app\n\nimport androidx.test.platform.app.InstrumentationRegistry\nimport androidx.test.ext.junit.runners.AndroidJUnit4\n\nimport org.junit.Test\nimport org.junit.runner.RunWith\n\nimport org.junit.Assert.*\n\n/**\n * Instrumented test, which will execute on an Android device.\n *\n * See [testing documentation](http://d.android.com/tools/testing).\n */\n@RunWith(AndroidJUnit4::class)\nclass ExampleInstrumentedTest {\n    @Test\n    fun useAppContext() {\n        // Context of the app under test.\n        val appContext = InstrumentationRegistry.getInstrumentation().targetContext\n        assertEquals(\"top.zibin.luban.app\", appContext.packageName)\n    }\n}"
  },
  {
    "path": "app/src/main/AndroidManifest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\">\n\n    <uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" />\n    <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"\n        android:maxSdkVersion=\"32\" />\n\n    <application\n        android:allowBackup=\"true\"\n        android:dataExtractionRules=\"@xml/data_extraction_rules\"\n        android:fullBackupContent=\"@xml/backup_rules\"\n        android:icon=\"@mipmap/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:roundIcon=\"@mipmap/ic_launcher_round\"\n        android:supportsRtl=\"true\"\n        android:theme=\"@style/Theme.KotlinLuban\">\n        <activity\n            android:name=\".MainActivity\"\n            android:exported=\"true\"\n            android:label=\"@string/app_name\"\n            android:theme=\"@style/Theme.KotlinLuban\">\n            <intent-filter>\n                <action android:name=\"android.intent.action.MAIN\" />\n\n                <category android:name=\"android.intent.category.LAUNCHER\" />\n            </intent-filter>\n        </activity>\n    </application>\n\n</manifest>"
  },
  {
    "path": "app/src/main/java/top/zibin/luban/app/MainActivity.kt",
    "content": "package top.zibin.luban.app\n\nimport android.os.Bundle\nimport androidx.activity.ComponentActivity\nimport androidx.activity.compose.rememberLauncherForActivityResult\nimport androidx.activity.compose.setContent\nimport androidx.activity.result.PickVisualMediaRequest\nimport androidx.activity.result.contract.ActivityResultContracts\nimport androidx.activity.viewModels\nimport androidx.compose.foundation.BorderStroke\nimport androidx.compose.foundation.background\nimport androidx.compose.foundation.border\nimport androidx.compose.foundation.clickable\nimport androidx.compose.foundation.layout.Arrangement\nimport androidx.compose.foundation.layout.Box\nimport androidx.compose.foundation.layout.Column\nimport androidx.compose.foundation.layout.PaddingValues\nimport androidx.compose.foundation.layout.Row\nimport androidx.compose.foundation.layout.Spacer\nimport androidx.compose.foundation.layout.fillMaxSize\nimport androidx.compose.foundation.layout.fillMaxWidth\nimport androidx.compose.foundation.layout.height\nimport androidx.compose.foundation.layout.padding\nimport androidx.compose.foundation.layout.size\nimport androidx.compose.foundation.layout.width\nimport androidx.compose.foundation.rememberScrollState\nimport androidx.compose.foundation.shape.RoundedCornerShape\nimport androidx.compose.foundation.verticalScroll\nimport androidx.compose.material.icons.Icons\nimport androidx.compose.material.icons.filled.Close\nimport androidx.compose.material.icons.filled.Compress\nimport androidx.compose.material.icons.filled.Fullscreen\nimport androidx.compose.material.icons.filled.Info\nimport androidx.compose.material.icons.filled.PhotoLibrary\nimport androidx.compose.material.icons.filled.PlayArrow\nimport androidx.compose.material3.Button\nimport androidx.compose.material3.Card\nimport androidx.compose.material3.CardDefaults\nimport androidx.compose.material3.CircularProgressIndicator\nimport androidx.compose.material3.ExperimentalMaterial3Api\nimport androidx.compose.material3.Icon\nimport androidx.compose.material3.IconButton\nimport androidx.compose.material3.MaterialTheme\nimport androidx.compose.material3.OutlinedTextField\nimport androidx.compose.material3.Scaffold\nimport androidx.compose.material3.Text\nimport androidx.compose.material3.TopAppBar\nimport androidx.compose.runtime.mutableStateOf\nimport androidx.compose.runtime.remember\nimport androidx.compose.runtime.Composable\nimport androidx.compose.runtime.LaunchedEffect\nimport androidx.compose.runtime.collectAsState\nimport androidx.compose.runtime.getValue\nimport androidx.compose.ui.Alignment\nimport androidx.compose.ui.Modifier\nimport androidx.compose.ui.draw.clip\nimport androidx.compose.ui.graphics.Color\nimport androidx.compose.ui.layout.ContentScale\nimport androidx.compose.ui.platform.LocalContext\nimport androidx.compose.ui.text.font.FontWeight\nimport androidx.compose.ui.unit.dp\nimport androidx.compose.ui.window.Dialog\nimport androidx.compose.ui.window.DialogProperties\nimport coil.compose.AsyncImage\nimport coil.request.ImageRequest\n\nclass MainActivity : ComponentActivity() {\n    private val viewModel: MainViewModel by viewModels()\n\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n        setContent {\n            MaterialTheme {\n                MainScreen(viewModel)\n            }\n        }\n    }\n}\n\n@OptIn(ExperimentalMaterial3Api::class)\n@Composable\nfun MainScreen(viewModel: MainViewModel) {\n    val uiState by viewModel.uiState.collectAsState()\n    val context = LocalContext.current\n\n    LaunchedEffect(Unit) {\n        viewModel.initStorageDirs(context)\n    }\n\n    val pickMedia =\n        rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->\n            if (uri != null) {\n                viewModel.onImageSelected(context, uri)\n            }\n        }\n\n    Scaffold(\n        topBar = {\n            TopAppBar(\n                title = { Text(\"图片压缩示例\") },\n                colors = androidx.compose.material3.TopAppBarDefaults.topAppBarColors(\n                    containerColor = MaterialTheme.colorScheme.primaryContainer,\n                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer\n                )\n            )\n        }\n    ) { innerPadding ->\n        Column(\n            modifier = Modifier\n                .fillMaxSize()\n                .padding(innerPadding)\n                .padding(16.dp)\n                .verticalScroll(rememberScrollState()),\n            verticalArrangement = Arrangement.spacedBy(16.dp)\n        ) {\n            if (uiState.appStorageDir != null) {\n                Card(\n                    modifier = Modifier.fillMaxWidth(),\n                    colors = CardDefaults.cardColors(\n                        containerColor = MaterialTheme.colorScheme.secondaryContainer\n                    ),\n                    shape = RoundedCornerShape(8.dp)\n                ) {\n                    Column(\n                        modifier = Modifier\n                            .fillMaxWidth()\n                            .padding(16.dp),\n                        verticalArrangement = Arrangement.spacedBy(12.dp)\n                    ) {\n                        Text(\n                            text = \"批量压缩测试\",\n                            style = MaterialTheme.typography.titleMedium,\n                            fontWeight = FontWeight.Bold\n                        )\n                        \n                        Text(\n                            text = \"输入目录: ${uiState.appStorageDir}\",\n                            style = MaterialTheme.typography.bodySmall,\n                            color = Color.Gray\n                        )\n                        \n                        Text(\n                            text = \"输出目录: ${uiState.outputStorageDir}\",\n                            style = MaterialTheme.typography.bodySmall,\n                            color = Color.Gray\n                        )\n                        \n                        if (uiState.isBatchCompressing) {\n                            Row(\n                                modifier = Modifier.fillMaxWidth(),\n                                verticalAlignment = Alignment.CenterVertically,\n                                horizontalArrangement = Arrangement.spacedBy(12.dp)\n                            ) {\n                                CircularProgressIndicator(\n                                    modifier = Modifier.size(24.dp),\n                                    strokeWidth = 2.dp\n                                )\n                                Text(\n                                    text = \"压缩中: ${uiState.batchProgress}/${uiState.batchTotal}\",\n                                    style = MaterialTheme.typography.bodyMedium\n                                )\n                            }\n                            \n                            androidx.compose.material3.LinearProgressIndicator(\n                                progress = { \n                                    if (uiState.batchTotal > 0) {\n                                        uiState.batchProgress.toFloat() / uiState.batchTotal.toFloat()\n                                    } else {\n                                        0f\n                                    }\n                                },\n                                modifier = Modifier.fillMaxWidth()\n                            )\n                        } else {\n                            Button(\n                                onClick = { viewModel.batchCompressImages(context) },\n                                modifier = Modifier.fillMaxWidth(),\n                                contentPadding = PaddingValues(vertical = 16.dp)\n                            ) {\n                                Icon(\n                                    imageVector = Icons.Default.PlayArrow,\n                                    contentDescription = null,\n                                    modifier = Modifier.size(18.dp)\n                                )\n                                Spacer(modifier = Modifier.width(8.dp))\n                                Text(\"开始批量压缩\")\n                            }\n                        }\n                        \n                        if (uiState.batchResult != null) {\n                            val result = uiState.batchResult!!\n                            Text(\n                                text = \"压缩完成: 总计 ${result.total}, 成功 ${result.success}, 失败 ${result.failed}\",\n                                style = MaterialTheme.typography.bodyMedium,\n                                fontWeight = FontWeight.Bold,\n                                color = if (result.failed == 0) Color(0xFF4CAF50) else Color(0xFFFF9800)\n                            )\n                            if (result.outputDir != null) {\n                                Text(\n                                    text = \"输出目录: ${result.outputDir.absolutePath}\",\n                                    style = MaterialTheme.typography.bodySmall,\n                                    color = Color.Gray\n                                )\n                            }\n                        }\n                    }\n                }\n            }\n            \n            Button(\n                onClick = {\n                    pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))\n                },\n                modifier = Modifier.fillMaxWidth(),\n                contentPadding = PaddingValues(vertical = 16.dp)\n            ) {\n                Icon(\n                    imageVector = Icons.Default.PhotoLibrary,\n                    contentDescription = null,\n                    modifier = Modifier.size(18.dp)\n                )\n                Spacer(modifier = Modifier.width(8.dp))\n                Text(\"从相册选择图片\")\n            }\n\n            Button(\n                onClick = { viewModel.compressImage(context) },\n                enabled = uiState.originalImage != null && !uiState.isCompressing,\n                modifier = Modifier.fillMaxWidth(),\n                contentPadding = PaddingValues(vertical = 16.dp)\n            ) {\n                if (uiState.isCompressing) {\n                    CircularProgressIndicator(\n                        modifier = Modifier.size(16.dp),\n                        strokeWidth = 2.dp,\n                        color = MaterialTheme.colorScheme.onPrimary\n                    )\n                    Spacer(modifier = Modifier.width(8.dp))\n                    Text(\"压缩中...\")\n                } else {\n                    Icon(\n                        imageVector = Icons.Default.Compress,\n                        contentDescription = null,\n                        modifier = Modifier.size(18.dp)\n                    )\n                    Spacer(modifier = Modifier.width(8.dp))\n                    Text(\"使用Luban算法压缩\")\n                }\n            }\n\n            if (uiState.error != null) {\n                Text(\n                    text = uiState.error!!,\n                    color = MaterialTheme.colorScheme.error,\n                    modifier = Modifier.fillMaxWidth()\n                )\n            }\n\n            if (uiState.compressionTarget != null && uiState.originalImage != null) {\n                CompressionTargetCard(\n                    originalWidth = uiState.originalImage!!.width,\n                    originalHeight = uiState.originalImage!!.height,\n                    target = uiState.compressionTarget!!,\n                    formatFileSize = viewModel::formatFileSize\n                )\n            }\n\n            if (uiState.originalImage != null) {\n                ImagePreviewCard(\n                    title = \"原图\",\n                    imageInfo = uiState.originalImage!!,\n                    formatFileSize = viewModel::formatFileSize,\n                    onClick = { viewModel.openImageViewer(uiState.originalImage!!) }\n                )\n            }\n\n            if (uiState.compressedImage != null) {\n                ImagePreviewCard(\n                    title = \"压缩后\",\n                    imageInfo = uiState.compressedImage!!,\n                    formatFileSize = viewModel::formatFileSize,\n                    onClick = { viewModel.openImageViewer(uiState.compressedImage!!) }\n                )\n            }\n\n            if (uiState.originalImage != null && uiState.compressedImage != null) {\n                ComparisonCard(\n                    originalSize = uiState.originalImage!!.size,\n                    compressedSize = uiState.compressedImage!!.size,\n                    formatFileSize = viewModel::formatFileSize\n                )\n            }\n        }\n    }\n\n    if (uiState.showImageViewer && uiState.viewingImage != null) {\n        FullScreenImageViewer(\n            imageInfo = uiState.viewingImage!!,\n            onClose = { viewModel.closeImageViewer() }\n        )\n    }\n}\n\n@Composable\nfun CompressionTargetCard(\n    originalWidth: Int,\n    originalHeight: Int,\n    target: top.zibin.luban.algorithm.CompressionTarget,\n    formatFileSize: (Long) -> String\n) {\n    val blue50 = Color(0xFFE3F2FD)\n    val blue200 = Color(0xFF90CAF9)\n    val blue700 = Color(0xFF1976D2)\n\n    Card(\n        modifier = Modifier.fillMaxWidth(),\n        colors = CardDefaults.cardColors(\n            containerColor = blue50\n        ),\n        border = BorderStroke(1.dp, blue200),\n        shape = RoundedCornerShape(8.dp)\n    ) {\n        Column(\n            modifier = Modifier\n                .fillMaxWidth()\n                .padding(12.dp),\n            verticalArrangement = Arrangement.spacedBy(8.dp)\n        ) {\n            Row(\n                verticalAlignment = Alignment.CenterVertically,\n                horizontalArrangement = Arrangement.spacedBy(8.dp)\n            ) {\n                Icon(\n                    imageVector = Icons.Default.Info,\n                    contentDescription = null,\n                    tint = blue700,\n                    modifier = Modifier.size(20.dp)\n                )\n                Text(\n                    text = \"Luban压缩参数\",\n                    style = MaterialTheme.typography.titleMedium,\n                    fontWeight = FontWeight.Bold,\n                    color = blue700\n                )\n            }\n\n            InfoRow(\n                label = \"原图尺寸\",\n                value = \"$originalWidth × $originalHeight\"\n            )\n\n            val sizeChanged = target.width != originalWidth || target.height != originalHeight\n            InfoRow(\n                label = \"目标尺寸\",\n                value = \"${target.width} × ${target.height}\",\n                highlight = sizeChanged\n            )\n\n            InfoRow(\n                label = \"压缩质量\",\n                value = \"60%\"\n            )\n\n            InfoRow(\n                label = \"预计大小\",\n                value = formatFileSize(target.estimatedSizeKb * 1024L)\n            )\n        }\n    }\n}\n\n@Composable\nfun InfoRow(\n    label: String,\n    value: String,\n    highlight: Boolean = false\n) {\n    Row(\n        modifier = Modifier.fillMaxWidth(),\n        horizontalArrangement = Arrangement.SpaceBetween\n    ) {\n        Text(\n            text = label,\n            style = MaterialTheme.typography.bodyMedium,\n            color = Color.Gray.copy(alpha = 0.7f)\n        )\n        Text(\n            text = value,\n            style = MaterialTheme.typography.bodyMedium,\n            fontWeight = if (highlight) FontWeight.Bold else FontWeight.Normal,\n            color = if (highlight) Color(0xFF1976D2) else Color.Black.copy(alpha = 0.87f)\n        )\n    }\n}\n\n@Composable\nfun ImagePreviewCard(\n    title: String,\n    imageInfo: ImageInfo,\n    formatFileSize: (Long) -> String,\n    onClick: () -> Unit\n) {\n    Column(\n        modifier = Modifier.fillMaxWidth(),\n        verticalArrangement = Arrangement.spacedBy(8.dp)\n    ) {\n        Text(\n            text = title,\n            style = MaterialTheme.typography.titleMedium,\n            fontWeight = FontWeight.Bold\n        )\n\n        Box(\n            modifier = Modifier\n                .fillMaxWidth()\n                .height(200.dp)\n                .clip(RoundedCornerShape(8.dp))\n                .border(1.dp, Color.Gray, RoundedCornerShape(8.dp))\n                .clickable(onClick = onClick)\n        ) {\n            val model = imageInfo.file ?: imageInfo.uri\n            AsyncImage(\n                model = ImageRequest.Builder(LocalContext.current)\n                    .data(model)\n                    .crossfade(true)\n                    .build(),\n                contentDescription = title,\n                modifier = Modifier.fillMaxSize(),\n                contentScale = ContentScale.Fit\n            )\n\n            Box(\n                modifier = Modifier\n                    .align(Alignment.TopEnd)\n                    .padding(8.dp)\n                    .background(\n                        Color.Black.copy(alpha = 0.5f),\n                        RoundedCornerShape(20.dp)\n                    )\n                    .padding(6.dp)\n            ) {\n                Icon(\n                    imageVector = Icons.Default.Fullscreen,\n                    contentDescription = \"全屏查看\",\n                    tint = Color.White,\n                    modifier = Modifier.size(18.dp)\n                )\n            }\n        }\n\n        Text(\n            text = \"大小: ${formatFileSize(imageInfo.size)}\",\n            style = MaterialTheme.typography.bodySmall,\n            color = Color.Gray\n        )\n        Text(\n            text = \"尺寸: ${imageInfo.width} × ${imageInfo.height}\",\n            style = MaterialTheme.typography.bodySmall,\n            color = Color.Gray\n        )\n    }\n}\n\n@Composable\nfun ComparisonCard(\n    originalSize: Long,\n    compressedSize: Long,\n    formatFileSize: (Long) -> String\n) {\n    val blue50 = Color(0xFFE3F2FD)\n    val compressionRatio = compressedSize.toFloat() / originalSize.toFloat()\n    val savedSize = originalSize - compressedSize\n    val ratioPercent = (1 - compressionRatio) * 100\n\n    val color = when {\n        ratioPercent > 50 -> Color(0xFF4CAF50)\n        ratioPercent > 20 -> Color(0xFF2196F3)\n        else -> Color(0xFFFF9800)\n    }\n\n    Card(\n        modifier = Modifier.fillMaxWidth(),\n        colors = CardDefaults.cardColors(\n            containerColor = blue50\n        ),\n        shape = RoundedCornerShape(8.dp)\n    ) {\n        Column(\n            modifier = Modifier\n                .fillMaxWidth()\n                .padding(16.dp),\n            verticalArrangement = Arrangement.spacedBy(12.dp)\n        ) {\n            Text(\n                text = \"压缩对比\",\n                style = MaterialTheme.typography.titleLarge,\n                fontWeight = FontWeight.Bold\n            )\n\n            ComparisonRow(\n                label = \"文件大小\",\n                original = formatFileSize(originalSize),\n                compressed = formatFileSize(compressedSize),\n                color = color\n            )\n\n            ComparisonRow(\n                label = \"压缩率\",\n                original = \"100%\",\n                compressed = \"${(compressionRatio * 100).toString().take(4)}%\",\n                color = color\n            )\n\n            ComparisonRow(\n                label = \"节省空间\",\n                original = \"-\",\n                compressed = formatFileSize(savedSize),\n                color = color\n            )\n        }\n    }\n}\n\n@Composable\nfun ComparisonRow(\n    label: String,\n    original: String,\n    compressed: String,\n    color: Color\n) {\n    Row(\n        modifier = Modifier.fillMaxWidth(),\n        horizontalArrangement = Arrangement.SpaceBetween,\n        verticalAlignment = Alignment.CenterVertically\n    ) {\n        Text(\n            text = label,\n            style = MaterialTheme.typography.bodyMedium,\n            fontWeight = FontWeight.Medium\n        )\n        Row(\n            verticalAlignment = Alignment.CenterVertically,\n            horizontalArrangement = Arrangement.spacedBy(8.dp)\n        ) {\n            Text(\n                text = original,\n                style = MaterialTheme.typography.bodyMedium,\n                color = Color.Gray\n            )\n            Text(\"→\", color = Color.Gray)\n            Text(\n                text = compressed,\n                style = MaterialTheme.typography.bodyMedium,\n                fontWeight = FontWeight.Bold,\n                color = color\n            )\n        }\n    }\n}\n\n@Composable\nfun FullScreenImageViewer(\n    imageInfo: ImageInfo,\n    onClose: () -> Unit\n) {\n    Dialog(\n        onDismissRequest = onClose,\n        properties = DialogProperties(\n            usePlatformDefaultWidth = false,\n            decorFitsSystemWindows = false\n        )\n    ) {\n        Box(\n            modifier = Modifier\n                .fillMaxSize()\n                .background(Color.Black)\n        ) {\n            val model = imageInfo.file ?: imageInfo.uri\n            AsyncImage(\n                model = ImageRequest.Builder(LocalContext.current)\n                    .data(model)\n                    .crossfade(true)\n                    .build(),\n                contentDescription = \"全屏图片\",\n                modifier = Modifier.fillMaxSize(),\n                contentScale = ContentScale.Fit\n            )\n\n            IconButton(\n                onClick = onClose,\n                modifier = Modifier\n                    .align(Alignment.TopEnd)\n                    .padding(16.dp)\n            ) {\n                Icon(\n                    imageVector = Icons.Default.Close,\n                    contentDescription = \"关闭\",\n                    tint = Color.White\n                )\n            }\n        }\n    }\n}"
  },
  {
    "path": "app/src/main/java/top/zibin/luban/app/MainViewModel.kt",
    "content": "package top.zibin.luban.app\n\nimport android.content.Context\nimport android.graphics.BitmapFactory\nimport android.net.Uri\nimport android.util.Log\nimport androidx.lifecycle.ViewModel\nimport androidx.lifecycle.viewModelScope\nimport kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.flow.MutableStateFlow\nimport kotlinx.coroutines.flow.StateFlow\nimport kotlinx.coroutines.flow.asStateFlow\nimport kotlinx.coroutines.flow.update\nimport kotlinx.coroutines.launch\nimport top.zibin.luban.api.Luban\nimport top.zibin.luban.api.luban\nimport top.zibin.luban.algorithm.CompressionCalculator\nimport top.zibin.luban.algorithm.CompressionTarget\nimport java.io.File\nimport java.io.FileOutputStream\nimport java.io.InputStream\nimport java.util.Locale\n\ndata class ImageInfo(\n    val uri: Uri? = null,\n    val file: File? = null,\n    val size: Long = 0,\n    val width: Int = 0,\n    val height: Int = 0\n)\n\ndata class BatchCompressResult(\n    val total: Int,\n    val success: Int,\n    val failed: Int,\n    val outputDir: File?\n)\n\ndata class MainUiState(\n    val originalImage: ImageInfo? = null,\n    val compressedImage: ImageInfo? = null,\n    val compressionTarget: CompressionTarget? = null,\n    val isCompressing: Boolean = false,\n    val error: String? = null,\n    val showImageViewer: Boolean = false,\n    val viewingImage: ImageInfo? = null,\n    val isBatchCompressing: Boolean = false,\n    val batchProgress: Int = 0,\n    val batchTotal: Int = 0,\n    val batchResult: BatchCompressResult? = null,\n    val appStorageDir: String? = null,\n    val outputStorageDir: String? = null\n)\n\nclass MainViewModel : ViewModel() {\n\n    private val _uiState = MutableStateFlow(MainUiState())\n    val uiState: StateFlow<MainUiState> = _uiState.asStateFlow()\n    private val calculator = CompressionCalculator()\n\n    fun onImageSelected(context: Context, uri: Uri) {\n        viewModelScope.launch(Dispatchers.IO) {\n            try {\n                val fileSize = context.contentResolver.openFileDescriptor(uri, \"r\")?.statSize ?: 0\n                val options = android.graphics.BitmapFactory.Options().apply {\n                    inJustDecodeBounds = true\n                }\n                context.contentResolver.openInputStream(uri)?.use {\n                    android.graphics.BitmapFactory.decodeStream(it, null, options)\n                }\n\n                val target = calculator.calculateTarget(options.outWidth, options.outHeight)\n\n                _uiState.update {\n                    it.copy(\n                        originalImage = ImageInfo(\n                            uri = uri,\n                            size = fileSize,\n                            width = options.outWidth,\n                            height = options.outHeight\n                        ),\n                        compressedImage = null,\n                        compressionTarget = target,\n                        error = null\n                    )\n                }\n            } catch (e: Exception) {\n                _uiState.update { it.copy(error = \"选择图片失败: ${e.message}\") }\n            }\n        }\n    }\n\n    fun compressImage(context: Context) {\n        val originalUri = _uiState.value.originalImage?.uri ?: return\n\n        viewModelScope.launch(Dispatchers.IO) {\n            _uiState.update { it.copy(isCompressing = true, error = null) }\n\n            val outputDir = File(context.cacheDir, \"luban_compressed\")\n            if (!outputDir.exists()) {\n                outputDir.mkdirs()\n            }\n\n            val results = luban(context) {\n                this.outputDir = outputDir\n                compress(originalUri)\n            }\n\n            val result = results.firstOrNull()\n                ?: Result.failure(IllegalStateException(\"No compression result\"))\n\n            result.getOrElse { error ->\n                _uiState.update {\n                    it.copy(isCompressing = false, error = \"压缩失败: ${error.message}\")\n                }\n                return@launch\n            }.let { file ->\n                val options = BitmapFactory.Options().apply {\n                    inJustDecodeBounds = true\n                }\n                BitmapFactory.decodeFile(file.absolutePath, options)\n\n                _uiState.update {\n                    it.copy(\n                        isCompressing = false,\n                        compressedImage = ImageInfo(\n                            file = file,\n                            size = file.length(),\n                            width = options.outWidth,\n                            height = options.outHeight\n                        )\n                    )\n                }\n            }\n        }\n    }\n\n    fun openImageViewer(imageInfo: ImageInfo) {\n        _uiState.update { it.copy(showImageViewer = true, viewingImage = imageInfo) }\n    }\n\n    fun closeImageViewer() {\n        _uiState.update { it.copy(showImageViewer = false, viewingImage = null) }\n    }\n\n    fun initStorageDirs(context: Context) {\n        viewModelScope.launch(Dispatchers.IO) {\n            val appStorageDir = getAppStorageDir(context)\n            val outputStorageDir = getOutputStorageDir(context)\n\n            appStorageDir?.let { dir ->\n                copyAssetsToStorage(context, dir)\n            }\n\n            _uiState.update {\n                it.copy(\n                    appStorageDir = appStorageDir?.absolutePath,\n                    outputStorageDir = outputStorageDir?.absolutePath\n                )\n            }\n        }\n    }\n\n    private fun copyAssetsToStorage(context: Context, targetDir: File) {\n        try {\n            val assetManager = context.assets\n            val assetFiles = assetManager.list(\"test_images\") ?: emptyArray()\n\n            if (assetFiles.isEmpty()) {\n                Log.d(\"AssetCopy\", \"assets/test_images 目录为空，跳过复制\")\n                return\n            }\n\n            val imageExtensions = setOf(\".jpg\", \".jpeg\", \".png\", \".webp\", \".bmp\")\n\n            assetFiles.forEach { fileName ->\n                val lowerFileName = fileName.lowercase()\n\n                val isImageFile = imageExtensions.any { lowerFileName.endsWith(it) }\n                if (!isImageFile) {\n                    Log.d(\"AssetCopy\", \"跳过非图片文件: $fileName\")\n                    return@forEach\n                }\n\n                val targetFile = File(targetDir, fileName)\n\n                if (targetFile.exists()) {\n                    Log.d(\"AssetCopy\", \"文件已存在，跳过: $fileName\")\n                    return@forEach\n                }\n\n                try {\n                    assetManager.open(\"test_images/$fileName\").use { input ->\n                        FileOutputStream(targetFile).use { output ->\n                            input.copyTo(output)\n                        }\n                    }\n                    Log.d(\"AssetCopy\", \"复制成功: $fileName\")\n                } catch (e: Exception) {\n                    Log.e(\"AssetCopy\", \"复制失败: $fileName\", e)\n                }\n            }\n        } catch (e: Exception) {\n            Log.e(\"AssetCopy\", \"复制assets图片失败\", e)\n        }\n    }\n\n    private fun getAppStorageDir(context: Context): File? {\n        val externalFilesDir = context.getExternalFilesDir(null)?.parentFile\n        return externalFilesDir?.let {\n            val appDir = File(it, \"images\")\n            if (!appDir.exists()) {\n                appDir.mkdirs()\n            }\n            appDir\n        }\n    }\n\n    private fun getOutputStorageDir(context: Context): File? {\n        val externalFilesDir = context.getExternalFilesDir(null)?.parentFile\n        return externalFilesDir?.let {\n            val outputDir = File(it, \"compressed\")\n            if (!outputDir.exists()) {\n                outputDir.mkdirs()\n            }\n            outputDir\n        }\n    }\n\n    fun batchCompressImages(context: Context) {\n        viewModelScope.launch(Dispatchers.IO) {\n            val inputDir = getAppStorageDir(context)\n            val outputDir = getOutputStorageDir(context)\n\n            if (inputDir == null || outputDir == null) {\n                _uiState.update {\n                    it.copy(error = \"无法访问存储目录，请检查权限\")\n                }\n                return@launch\n            }\n\n            if (!inputDir.exists()) {\n                _uiState.update {\n                    it.copy(error = \"输入目录不存在: ${inputDir.absolutePath}\")\n                }\n                return@launch\n            }\n\n            val imageFiles = inputDir.listFiles { file ->\n                file.isFile && (file.name.endsWith(\".jpg\", ignoreCase = true)\n                        || file.name.endsWith(\".jpeg\", ignoreCase = true)\n                        || file.name.endsWith(\".png\", ignoreCase = true))\n            } ?: emptyArray()\n\n            if (imageFiles.isEmpty()) {\n                _uiState.update {\n                    it.copy(error = \"输入目录中没有找到图片文件: ${inputDir.absolutePath}\")\n                }\n                return@launch\n            }\n\n            _uiState.update {\n                it.copy(\n                    isBatchCompressing = true,\n                    batchProgress = 0,\n                    batchTotal = imageFiles.size,\n                    batchResult = null,\n                    error = null\n                )\n            }\n\n            val inputList = imageFiles.toList()\n            Log.d(\"BatchCompress\", \"开始批量压缩，共 ${inputList.size} 张图片\")\n\n            val results = luban(context) {\n                this.outputDir = outputDir\n                compress(inputList)\n            }\n\n            var successCount = 0\n            var failedCount = 0\n\n            results.forEachIndexed { index, result ->\n                val inputFile = inputList[index]\n\n                result.getOrNull()?.let { compressedFile ->\n                    successCount++\n\n                    val options = BitmapFactory.Options().apply {\n                        inJustDecodeBounds = true\n                    }\n                    BitmapFactory.decodeFile(compressedFile.absolutePath, options)\n\n                    val width = options.outWidth\n                    val height = options.outHeight\n                    val fileSize = compressedFile.length()\n                    val fileSizeKB = fileSize / 1024.0\n                    val fileSizeMB = fileSizeKB / 1024.0\n\n                    val sizeStr = when {\n                        fileSizeMB >= 1.0 -> String.format(\"%.2f MB\", fileSizeMB)\n                        else -> String.format(\"%.2f KB\", fileSizeKB)\n                    }\n\n                    Log.d(\n                        \"BatchCompress\",\n                        \"[${index + 1}/${inputList.size}] 压缩成功: \" +\n                                \"文件名=${compressedFile.name}, \" +\n                                \"分辨率=${width}×${height}, \" +\n                                \"文件大小=${sizeStr} (${fileSize} bytes)\"\n                    )\n                } ?: run {\n                    failedCount++\n                    val error = result.exceptionOrNull()\n                    Log.e(\n                        \"BatchCompress\",\n                        \"[${index + 1}/${inputList.size}] 压缩失败: ${inputFile.name}, 错误=${error?.message}\"\n                    )\n                }\n\n                _uiState.update {\n                    it.copy(batchProgress = index + 1)\n                }\n            }\n\n            Log.d(\n                \"BatchCompress\",\n                \"批量压缩完成: 总计=${inputList.size}, 成功=${successCount}, 失败=${failedCount}\"\n            )\n\n            _uiState.update {\n                it.copy(\n                    isBatchCompressing = false,\n                    batchResult = BatchCompressResult(\n                        total = inputList.size,\n                        success = successCount,\n                        failed = failedCount,\n                        outputDir = outputDir\n                    )\n                )\n            }\n        }\n    }\n\n    fun formatFileSize(size: Long): String {\n        if (size <= 0) return \"0 B\"\n        val units = arrayOf(\"B\", \"KB\", \"MB\", \"GB\", \"TB\")\n        val digitGroups = (Math.log10(size.toDouble()) / Math.log10(1024.0)).toInt()\n        return String.format(\n            Locale.US,\n            \"%.2f %s\",\n            size / Math.pow(1024.0, digitGroups.toDouble()),\n            units[digitGroups]\n        )\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/top/zibin/luban/app/ui/theme/Color.kt",
    "content": "package top.zibin.luban.app.ui.theme\n\nimport androidx.compose.ui.graphics.Color\n\nval Purple80 = Color(0xFFD0BCFF)\nval PurpleGrey80 = Color(0xFFCCC2DC)\nval Pink80 = Color(0xFFEFB8C8)\n\nval Purple40 = Color(0xFF6650a4)\nval PurpleGrey40 = Color(0xFF625b71)\nval Pink40 = Color(0xFF7D5260)"
  },
  {
    "path": "app/src/main/java/top/zibin/luban/app/ui/theme/Theme.kt",
    "content": "package top.zibin.luban.app.ui.theme\n\nimport android.app.Activity\nimport android.os.Build\nimport androidx.compose.foundation.isSystemInDarkTheme\nimport androidx.compose.material3.MaterialTheme\nimport androidx.compose.material3.darkColorScheme\nimport androidx.compose.material3.dynamicDarkColorScheme\nimport androidx.compose.material3.dynamicLightColorScheme\nimport androidx.compose.material3.lightColorScheme\nimport androidx.compose.runtime.Composable\nimport androidx.compose.ui.platform.LocalContext\n\nprivate val DarkColorScheme = darkColorScheme(\n    primary = Purple80,\n    secondary = PurpleGrey80,\n    tertiary = Pink80\n)\n\nprivate val LightColorScheme = lightColorScheme(\n    primary = Purple40,\n    secondary = PurpleGrey40,\n    tertiary = Pink40\n\n    /* Other default colors to override\n    background = Color(0xFFFFFBFE),\n    surface = Color(0xFFFFFBFE),\n    onPrimary = Color.White,\n    onSecondary = Color.White,\n    onTertiary = Color.White,\n    onBackground = Color(0xFF1C1B1F),\n    onSurface = Color(0xFF1C1B1F),\n    */\n)\n\n@Composable\nfun KotlinLubanTheme(\n    darkTheme: Boolean = isSystemInDarkTheme(),\n    // Dynamic color is available on Android 12+\n    dynamicColor: Boolean = true,\n    content: @Composable () -> Unit\n) {\n    val colorScheme = when {\n        dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {\n            val context = LocalContext.current\n            if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)\n        }\n\n        darkTheme -> DarkColorScheme\n        else -> LightColorScheme\n    }\n\n    MaterialTheme(\n        colorScheme = colorScheme,\n        typography = Typography,\n        content = content\n    )\n}"
  },
  {
    "path": "app/src/main/java/top/zibin/luban/app/ui/theme/Type.kt",
    "content": "package top.zibin.luban.app.ui.theme\n\nimport androidx.compose.material3.Typography\nimport androidx.compose.ui.text.TextStyle\nimport androidx.compose.ui.text.font.FontFamily\nimport androidx.compose.ui.text.font.FontWeight\nimport androidx.compose.ui.unit.sp\n\n// Set of Material typography styles to start with\nval Typography = Typography(\n    bodyLarge = TextStyle(\n        fontFamily = FontFamily.Default,\n        fontWeight = FontWeight.Normal,\n        fontSize = 16.sp,\n        lineHeight = 24.sp,\n        letterSpacing = 0.5.sp\n    )\n    /* Other default text styles to override\n    titleLarge = TextStyle(\n        fontFamily = FontFamily.Default,\n        fontWeight = FontWeight.Normal,\n        fontSize = 22.sp,\n        lineHeight = 28.sp,\n        letterSpacing = 0.sp\n    ),\n    labelSmall = TextStyle(\n        fontFamily = FontFamily.Default,\n        fontWeight = FontWeight.Medium,\n        fontSize = 11.sp,\n        lineHeight = 16.sp,\n        letterSpacing = 0.5.sp\n    )\n    */\n)"
  },
  {
    "path": "app/src/main/res/drawable/ic_launcher_background.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:width=\"108dp\"\n    android:height=\"108dp\"\n    android:viewportWidth=\"108\"\n    android:viewportHeight=\"108\">\n    <path\n        android:fillColor=\"#3DDC84\"\n        android:pathData=\"M0,0h108v108h-108z\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M9,0L9,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,0L19,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M29,0L29,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M39,0L39,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M49,0L49,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M59,0L59,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M69,0L69,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M79,0L79,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M89,0L89,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M99,0L99,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,9L108,9\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,19L108,19\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,29L108,29\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,39L108,39\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,49L108,49\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,59L108,59\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,69L108,69\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,79L108,79\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,89L108,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,99L108,99\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,29L89,29\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,39L89,39\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,49L89,49\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,59L89,59\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,69L89,69\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,79L89,79\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M29,19L29,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M39,19L39,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M49,19L49,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M59,19L59,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M69,19L69,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M79,19L79,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n</vector>\n"
  },
  {
    "path": "app/src/main/res/drawable/ic_launcher_foreground.xml",
    "content": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:aapt=\"http://schemas.android.com/aapt\"\n    android:width=\"108dp\"\n    android:height=\"108dp\"\n    android:viewportWidth=\"108\"\n    android:viewportHeight=\"108\">\n    <path android:pathData=\"M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z\">\n        <aapt:attr name=\"android:fillColor\">\n            <gradient\n                android:endX=\"85.84757\"\n                android:endY=\"92.4963\"\n                android:startX=\"42.9492\"\n                android:startY=\"49.59793\"\n                android:type=\"linear\">\n                <item\n                    android:color=\"#44000000\"\n                    android:offset=\"0.0\" />\n                <item\n                    android:color=\"#00000000\"\n                    android:offset=\"1.0\" />\n            </gradient>\n        </aapt:attr>\n    </path>\n    <path\n        android:fillColor=\"#FFFFFF\"\n        android:fillType=\"nonZero\"\n        android:pathData=\"M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z\"\n        android:strokeWidth=\"1\"\n        android:strokeColor=\"#00000000\" />\n</vector>"
  },
  {
    "path": "app/src/main/res/mipmap-anydpi/ic_launcher.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<adaptive-icon xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <background android:drawable=\"@drawable/ic_launcher_background\" />\n    <foreground android:drawable=\"@drawable/ic_launcher_foreground\" />\n    <monochrome android:drawable=\"@drawable/ic_launcher_foreground\" />\n</adaptive-icon>"
  },
  {
    "path": "app/src/main/res/mipmap-anydpi/ic_launcher_round.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<adaptive-icon xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <background android:drawable=\"@drawable/ic_launcher_background\" />\n    <foreground android:drawable=\"@drawable/ic_launcher_foreground\" />\n    <monochrome android:drawable=\"@drawable/ic_launcher_foreground\" />\n</adaptive-icon>"
  },
  {
    "path": "app/src/main/res/values/colors.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <color name=\"purple_200\">#FFBB86FC</color>\n    <color name=\"purple_500\">#FF6200EE</color>\n    <color name=\"purple_700\">#FF3700B3</color>\n    <color name=\"teal_200\">#FF03DAC5</color>\n    <color name=\"teal_700\">#FF018786</color>\n    <color name=\"black\">#FF000000</color>\n    <color name=\"white\">#FFFFFFFF</color>\n</resources>"
  },
  {
    "path": "app/src/main/res/values/strings.xml",
    "content": "<resources>\n    <string name=\"app_name\">Kotlin Luban</string>\n</resources>"
  },
  {
    "path": "app/src/main/res/values/themes.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n\n    <style name=\"Theme.KotlinLuban\" parent=\"android:Theme.Material.Light.NoActionBar\" />\n</resources>"
  },
  {
    "path": "app/src/main/res/xml/backup_rules.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--\n   Sample backup rules file; uncomment and customize as necessary.\n   See https://developer.android.com/guide/topics/data/autobackup\n   for details.\n   Note: This file is ignored for devices older than API 31\n   See https://developer.android.com/about/versions/12/backup-restore\n-->\n<full-backup-content>\n    <!--\n   <include domain=\"sharedpref\" path=\".\"/>\n   <exclude domain=\"sharedpref\" path=\"device.xml\"/>\n-->\n</full-backup-content>"
  },
  {
    "path": "app/src/main/res/xml/data_extraction_rules.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--\n   Sample data extraction rules file; uncomment and customize as necessary.\n   See https://developer.android.com/about/versions/12/backup-restore#xml-changes\n   for details.\n-->\n<data-extraction-rules>\n    <cloud-backup>\n        <!-- TODO: Use <include> and <exclude> to control what is backed up.\n        <include .../>\n        <exclude .../>\n        -->\n    </cloud-backup>\n    <!--\n    <device-transfer>\n        <include .../>\n        <exclude .../>\n    </device-transfer>\n    -->\n</data-extraction-rules>"
  },
  {
    "path": "app/src/test/java/top/zibin/luban/app/ExampleUnitTest.kt",
    "content": "package top.zibin.luban.app\n\nimport org.junit.Test\n\nimport org.junit.Assert.*\n\n/**\n * Example local unit test, which will execute on the development machine (host).\n *\n * See [testing documentation](http://d.android.com/tools/testing).\n */\nclass ExampleUnitTest {\n    @Test\n    fun addition_isCorrect() {\n        assertEquals(4, 2 + 2)\n    }\n}"
  },
  {
    "path": "app-java/.gitignore",
    "content": "/build"
  },
  {
    "path": "app-java/build.gradle.kts",
    "content": "plugins {\n    alias(libs.plugins.android.application)\n}\n\nandroid {\n    namespace = \"top.zibin.luban.app.java\"\n    compileSdk = 36\n\n    defaultConfig {\n        applicationId = \"top.zibin.luban.app.java\"\n        minSdk = 26\n        targetSdk = 34\n        versionCode = 1\n        versionName = \"1.0\"\n\n        testInstrumentationRunner = \"androidx.test.runner.AndroidJUnitRunner\"\n    }\n\n    buildTypes {\n        release {\n            isMinifyEnabled = false\n            proguardFiles(\n                getDefaultProguardFile(\"proguard-android-optimize.txt\"),\n                \"proguard-rules.pro\"\n            )\n        }\n    }\n    compileOptions {\n        sourceCompatibility = JavaVersion.VERSION_1_8\n        targetCompatibility = JavaVersion.VERSION_1_8\n    }\n}\n\ndependencies {\n    implementation(project(\":luban\"))\n    implementation(libs.androidx.appcompat)\n    implementation(libs.material)\n    testImplementation(libs.junit)\n    androidTestImplementation(libs.androidx.junit)\n    androidTestImplementation(libs.androidx.espresso.core)\n}"
  },
  {
    "path": "app-java/proguard-rules.pro",
    "content": "# Add project specific ProGuard rules here.\n# You can control the set of applied configuration files using the\n# proguardFiles setting in build.gradle.\n#\n# For more details, see\n#   http://developer.android.com/guide/developing/tools/proguard.html\n\n# If your project uses WebView with JS, uncomment the following\n# and specify the fully qualified class name to the JavaScript interface\n# class:\n#-keepclassmembers class fqcn.of.javascript.interface.for.webview {\n#   public *;\n#}\n\n# Uncomment this to preserve the line number information for\n# debugging stack traces.\n#-keepattributes SourceFile,LineNumberTable\n\n# If you keep the line number information, uncomment this to\n# hide the original source file name.\n#-renamesourcefileattribute SourceFile"
  },
  {
    "path": "app-java/src/androidTest/java/top/zibin/luban/app/java/ExampleInstrumentedTest.java",
    "content": "package top.zibin.luban.app.java;\n\nimport android.content.Context;\n\nimport androidx.test.platform.app.InstrumentationRegistry;\nimport androidx.test.ext.junit.runners.AndroidJUnit4;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n\nimport static org.junit.Assert.*;\n\n/**\n * Instrumented test, which will execute on an Android device.\n *\n * @see <a href=\"http://d.android.com/tools/testing\">Testing documentation</a>\n */\n@RunWith(AndroidJUnit4.class)\npublic class ExampleInstrumentedTest {\n    @Test\n    public void useAppContext() {\n        // Context of the app under test.\n        Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();\n        assertEquals(\"top.zibin.luban.app.java\", appContext.getPackageName());\n    }\n}"
  },
  {
    "path": "app-java/src/main/AndroidManifest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\">\n\n    <uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" />\n    <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"\n        tools:ignore=\"ScopedStorage\" />\n\n    <application\n        android:allowBackup=\"true\"\n        android:dataExtractionRules=\"@xml/data_extraction_rules\"\n        android:fullBackupContent=\"@xml/backup_rules\"\n        android:icon=\"@mipmap/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:roundIcon=\"@mipmap/ic_launcher_round\"\n        android:supportsRtl=\"true\"\n        android:theme=\"@style/Theme.Luban\"\n        tools:targetApi=\"31\">\n        <activity\n            android:name=\".MainActivity\"\n            android:exported=\"true\">\n            <intent-filter>\n                <action android:name=\"android.intent.action.MAIN\" />\n\n                <category android:name=\"android.intent.category.LAUNCHER\" />\n            </intent-filter>\n        </activity>\n    </application>\n\n</manifest>"
  },
  {
    "path": "app-java/src/main/java/top/zibin/luban/app/java/MainActivity.java",
    "content": "package top.zibin.luban.app.java;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.graphics.BitmapFactory;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.provider.MediaStore;\nimport android.util.Log;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport androidx.annotation.Nullable;\nimport androidx.appcompat.app.AppCompatActivity;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\n\nimport top.zibin.luban.api.Luban;\nimport top.zibin.luban.api.OnCompressListener;\n\npublic class MainActivity extends AppCompatActivity {\n\n    private static final int REQUEST_CODE_SELECT_IMAGE = 100;\n    private static final String TAG = \"LubanJava\";\n\n    private ImageView ivOriginal;\n    private TextView tvOriginalSize;\n    private TextView tvOriginalDimens;\n    private ImageView ivCompressed;\n    private TextView tvCompressedSize;\n    private TextView tvCompressedDimens;\n    private TextView tvStatus;\n    private Button btnCompress;\n\n    private Uri selectedUri;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        initViews();\n        initStorageDirs();\n    }\n    \n    private void initStorageDirs() {\n        new Thread(() -> {\n            File appStorageDir = getAppStorageDir();\n            File outputStorageDir = getOutputStorageDir();\n            \n            if (appStorageDir != null) {\n                copyAssetsToStorage(appStorageDir);\n            }\n        }).start();\n    }\n    \n    private File getAppStorageDir() {\n        File externalFilesDir = getExternalFilesDir(null);\n        if (externalFilesDir == null) return null;\n        \n        File parentFile = externalFilesDir.getParentFile();\n        if (parentFile == null) return null;\n        \n        File appDir = new File(parentFile, \"images\");\n        if (!appDir.exists()) {\n            appDir.mkdirs();\n        }\n        return appDir;\n    }\n    \n    private File getOutputStorageDir() {\n        File externalFilesDir = getExternalFilesDir(null);\n        if (externalFilesDir == null) return null;\n        \n        File parentFile = externalFilesDir.getParentFile();\n        if (parentFile == null) return null;\n        \n        File outputDir = new File(parentFile, \"compressed\");\n        if (!outputDir.exists()) {\n            outputDir.mkdirs();\n        }\n        return outputDir;\n    }\n    \n    private void copyAssetsToStorage(File targetDir) {\n        try {\n            String[] assetFiles = getAssets().list(\"test_images\");\n            if (assetFiles == null || assetFiles.length == 0) {\n                Log.d(TAG, \"assets/test_images 目录为空，跳过复制\");\n                return;\n            }\n            \n            String[] imageExtensions = {\".jpg\", \".jpeg\", \".png\", \".webp\", \".bmp\"};\n            \n            for (String fileName : assetFiles) {\n                String lowerFileName = fileName.toLowerCase();\n                \n                boolean isImageFile = false;\n                for (String ext : imageExtensions) {\n                    if (lowerFileName.endsWith(ext)) {\n                        isImageFile = true;\n                        break;\n                    }\n                }\n                if (!isImageFile) {\n                    Log.d(TAG, \"跳过非图片文件: \" + fileName);\n                    continue;\n                }\n                \n                File targetFile = new File(targetDir, fileName);\n                \n                if (targetFile.exists()) {\n                    Log.d(TAG, \"文件已存在，跳过: \" + fileName);\n                    continue;\n                }\n                \n                try (InputStream input = getAssets().open(\"test_images/\" + fileName);\n                     FileOutputStream output = new FileOutputStream(targetFile)) {\n                    \n                    byte[] buffer = new byte[4096];\n                    int bytesRead;\n                    while ((bytesRead = input.read(buffer)) != -1) {\n                        output.write(buffer, 0, bytesRead);\n                    }\n                    \n                    Log.d(TAG, \"复制成功: \" + fileName);\n                } catch (IOException e) {\n                    Log.e(TAG, \"复制失败: \" + fileName, e);\n                }\n            }\n        } catch (IOException e) {\n            Log.e(TAG, \"复制assets图片失败\", e);\n        }\n    }\n\n    private void initViews() {\n        Button btnSelect = findViewById(R.id.btn_select_image);\n        btnCompress = findViewById(R.id.btn_compress_image);\n        Button btnBatchCompress = findViewById(R.id.btn_batch_compress);\n        \n        ivOriginal = findViewById(R.id.iv_original);\n        tvOriginalSize = findViewById(R.id.tv_original_size);\n        tvOriginalDimens = findViewById(R.id.tv_original_dimens);\n        \n        ivCompressed = findViewById(R.id.iv_compressed);\n        tvCompressedSize = findViewById(R.id.tv_compressed_size);\n        tvCompressedDimens = findViewById(R.id.tv_compressed_dimens);\n        \n        tvStatus = findViewById(R.id.tv_status);\n\n        btnSelect.setOnClickListener(v -> openGallery());\n        btnCompress.setOnClickListener(v -> compressImage());\n        btnBatchCompress.setOnClickListener(v -> batchCompress());\n    }\n\n    private void openGallery() {\n        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);\n        startActivityForResult(intent, REQUEST_CODE_SELECT_IMAGE);\n    }\n\n    @Override\n    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {\n        super.onActivityResult(requestCode, resultCode, data);\n        if (requestCode == REQUEST_CODE_SELECT_IMAGE && resultCode == RESULT_OK && data != null) {\n            selectedUri = data.getData();\n            if (selectedUri != null) {\n                displayOriginalImage(selectedUri);\n                btnCompress.setEnabled(true);\n                // Reset compressed view\n                ivCompressed.setImageDrawable(null);\n                tvCompressedSize.setText(\"\");\n                tvCompressedDimens.setText(\"\");\n                tvStatus.setText(\"\");\n            }\n        }\n    }\n\n    private void displayOriginalImage(Uri uri) {\n        ivOriginal.setImageURI(uri);\n        \n        try {\n            InputStream is = getContentResolver().openInputStream(uri);\n            if (is != null) {\n                int size = is.available();\n                tvOriginalSize.setText(String.format(getString(R.string.file_size), formatFileSize(size)));\n                is.close();\n            }\n            \n            BitmapFactory.Options options = new BitmapFactory.Options();\n            options.inJustDecodeBounds = true;\n            InputStream is2 = getContentResolver().openInputStream(uri);\n            BitmapFactory.decodeStream(is2, null, options);\n            if (is2 != null) is2.close();\n            \n            tvOriginalDimens.setText(String.format(Locale.getDefault(), getString(R.string.image_size), options.outWidth, options.outHeight));\n            \n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n\n    private void compressImage() {\n        if (selectedUri == null) return;\n        \n        tvStatus.setText(\"Compressing...\");\n        \n        File outputDir = new File(getExternalFilesDir(null), \"compressed\");\n        if (!outputDir.exists()) {\n            outputDir.mkdirs();\n        }\n\n        // Use the Java compatible Builder API\n        Luban.with(this)\n                .load(selectedUri)\n                .setTargetDir(outputDir)\n                .bindLifecycle(this)\n                .setCompressListener(new OnCompressListener() {\n                    @Override\n                    public void onStart() {\n                        Log.d(TAG, \"Compression started\");\n                    }\n\n                    @Override\n                    public void onSuccess(File file) {\n                        Log.d(TAG, \"Compression success: \" + file.getAbsolutePath());\n                        tvStatus.setText(getString(R.string.compress_success));\n                        displayCompressedImage(file);\n                    }\n\n                    @Override\n                    public void onError(Throwable e) {\n                        Log.e(TAG, \"Compression error\", e);\n                        tvStatus.setText(String.format(getString(R.string.compress_failed), e.getMessage()));\n                    }\n                })\n                .launch();\n    }\n    \n    private void displayCompressedImage(File file) {\n        ivCompressed.setImageURI(Uri.fromFile(file));\n        \n        long size = file.length();\n        tvCompressedSize.setText(String.format(getString(R.string.file_size), formatFileSize(size)));\n        \n        BitmapFactory.Options options = new BitmapFactory.Options();\n        options.inJustDecodeBounds = true;\n        BitmapFactory.decodeFile(file.getAbsolutePath(), options);\n        \n        tvCompressedDimens.setText(String.format(Locale.getDefault(), getString(R.string.image_size), options.outWidth, options.outHeight));\n    }\n    \n    private void batchCompress() {\n        File inputDir = new File(getExternalFilesDir(null).getParentFile(), \"images\");\n        if (!inputDir.exists() || !inputDir.isDirectory()) {\n            Toast.makeText(this, \"Please put images in \" + inputDir.getAbsolutePath(), Toast.LENGTH_LONG).show();\n            return;\n        }\n        \n        File[] files = inputDir.listFiles((dir, name) -> {\n            String lower = name.toLowerCase();\n            return lower.endsWith(\".jpg\") || lower.endsWith(\".jpeg\") || lower.endsWith(\".png\");\n        });\n        \n        if (files == null || files.length == 0) {\n            Toast.makeText(this, \"No images found in \" + inputDir.getAbsolutePath(), Toast.LENGTH_SHORT).show();\n            return;\n        }\n        \n        File outputDir = new File(getExternalFilesDir(null).getParentFile(), \"compressed\");\n        \n        List<File> fileList = new ArrayList<>();\n        for (File f : files) {\n            fileList.add(f);\n        }\n        \n        tvStatus.setText(\"Batch compressing \" + fileList.size() + \" images...\");\n        \n        final int[] successCount = {0};\n        final int[] failedCount = {0};\n        final int total = fileList.size();\n        \n        Luban.with(this)\n                .load(fileList)\n                .setTargetDir(outputDir)\n                .bindLifecycle(this)\n                .setCompressListener(new OnCompressListener() {\n                    @Override\n                    public void onStart() {\n                        // Batch start\n                    }\n\n                    @Override\n                    public void onSuccess(File file) {\n                        successCount[0]++;\n                        checkBatchComplete(total, successCount[0], failedCount[0]);\n                    }\n\n                    @Override\n                    public void onError(Throwable e) {\n                        failedCount[0]++;\n                        checkBatchComplete(total, successCount[0], failedCount[0]);\n                    }\n                })\n                .launch();\n    }\n    \n    private void checkBatchComplete(int total, int success, int failed) {\n        if (success + failed >= total) {\n            String msg = String.format(Locale.getDefault(), getString(R.string.batch_compress_result), total, success, failed);\n            tvStatus.setText(msg);\n            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();\n        } else {\n            tvStatus.setText(\"Processing: \" + (success + failed) + \"/\" + total);\n        }\n    }\n\n    private String formatFileSize(long size) {\n        if (size <= 0) return \"0 B\";\n        final String[] units = new String[]{\"B\", \"KB\", \"MB\", \"GB\", \"TB\"};\n        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));\n        return String.format(Locale.US, \"%.2f %s\", size / Math.pow(1024, digitGroups), units[digitGroups]);\n    }\n}"
  },
  {
    "path": "app-java/src/main/res/drawable/ic_launcher_background.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:width=\"108dp\"\n    android:height=\"108dp\"\n    android:viewportWidth=\"108\"\n    android:viewportHeight=\"108\">\n    <path\n        android:fillColor=\"#3DDC84\"\n        android:pathData=\"M0,0h108v108h-108z\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M9,0L9,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,0L19,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M29,0L29,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M39,0L39,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M49,0L49,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M59,0L59,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M69,0L69,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M79,0L79,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M89,0L89,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M99,0L99,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,9L108,9\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,19L108,19\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,29L108,29\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,39L108,39\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,49L108,49\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,59L108,59\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,69L108,69\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,79L108,79\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,89L108,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,99L108,99\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,29L89,29\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,39L89,39\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,49L89,49\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,59L89,59\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,69L89,69\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,79L89,79\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M29,19L29,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M39,19L39,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M49,19L49,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M59,19L59,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M69,19L69,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M79,19L79,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n</vector>\n"
  },
  {
    "path": "app-java/src/main/res/drawable/ic_launcher_foreground.xml",
    "content": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:aapt=\"http://schemas.android.com/aapt\"\n    android:width=\"108dp\"\n    android:height=\"108dp\"\n    android:viewportWidth=\"108\"\n    android:viewportHeight=\"108\">\n    <path android:pathData=\"M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z\">\n        <aapt:attr name=\"android:fillColor\">\n            <gradient\n                android:endX=\"85.84757\"\n                android:endY=\"92.4963\"\n                android:startX=\"42.9492\"\n                android:startY=\"49.59793\"\n                android:type=\"linear\">\n                <item\n                    android:color=\"#44000000\"\n                    android:offset=\"0.0\" />\n                <item\n                    android:color=\"#00000000\"\n                    android:offset=\"1.0\" />\n            </gradient>\n        </aapt:attr>\n    </path>\n    <path\n        android:fillColor=\"#FFFFFF\"\n        android:fillType=\"nonZero\"\n        android:pathData=\"M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z\"\n        android:strokeWidth=\"1\"\n        android:strokeColor=\"#00000000\" />\n</vector>"
  },
  {
    "path": "app-java/src/main/res/layout/activity_main.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ScrollView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:padding=\"16dp\">\n\n    <LinearLayout\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:orientation=\"vertical\"\n        android:gravity=\"center_horizontal\">\n\n        <Button\n            android:id=\"@+id/btn_select_image\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:text=\"@string/select_image\" />\n\n        <Button\n            android:id=\"@+id/btn_compress_image\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:text=\"@string/compress_image\"\n            android:enabled=\"false\" />\n            \n        <Button\n            android:id=\"@+id/btn_batch_compress\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:text=\"@string/batch_compress\" />\n\n        <TextView\n            android:id=\"@+id/tv_status\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:layout_marginTop=\"8dp\"\n            android:textColor=\"#FF0000\"\n            android:gravity=\"center\" />\n\n        <LinearLayout\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:orientation=\"horizontal\"\n            android:layout_marginTop=\"16dp\"\n            android:baselineAligned=\"false\">\n\n            <LinearLayout\n                android:layout_width=\"0dp\"\n                android:layout_height=\"wrap_content\"\n                android:layout_weight=\"1\"\n                android:orientation=\"vertical\"\n                android:gravity=\"center\">\n\n                <TextView\n                    android:layout_width=\"wrap_content\"\n                    android:layout_height=\"wrap_content\"\n                    android:text=\"@string/original_image\"\n                    android:textStyle=\"bold\" />\n\n                <ImageView\n                    android:id=\"@+id/iv_original\"\n                    android:layout_width=\"match_parent\"\n                    android:layout_height=\"200dp\"\n                    android:scaleType=\"fitCenter\"\n                    android:background=\"#EEEEEE\"\n                    android:layout_marginTop=\"8dp\" />\n\n                <TextView\n                    android:id=\"@+id/tv_original_size\"\n                    android:layout_width=\"wrap_content\"\n                    android:layout_height=\"wrap_content\"\n                    android:layout_marginTop=\"4dp\"\n                    tools:text=\"大小: 2.5 MB\" />\n\n                <TextView\n                    android:id=\"@+id/tv_original_dimens\"\n                    android:layout_width=\"wrap_content\"\n                    android:layout_height=\"wrap_content\"\n                    tools:text=\"尺寸: 1920 x 1080\" />\n            </LinearLayout>\n\n            <Space\n                android:layout_width=\"16dp\"\n                android:layout_height=\"wrap_content\" />\n\n            <LinearLayout\n                android:layout_width=\"0dp\"\n                android:layout_height=\"wrap_content\"\n                android:layout_weight=\"1\"\n                android:orientation=\"vertical\"\n                android:gravity=\"center\">\n\n                <TextView\n                    android:layout_width=\"wrap_content\"\n                    android:layout_height=\"wrap_content\"\n                    android:text=\"@string/compressed_image\"\n                    android:textStyle=\"bold\" />\n\n                <ImageView\n                    android:id=\"@+id/iv_compressed\"\n                    android:layout_width=\"match_parent\"\n                    android:layout_height=\"200dp\"\n                    android:scaleType=\"fitCenter\"\n                    android:background=\"#EEEEEE\"\n                    android:layout_marginTop=\"8dp\" />\n\n                <TextView\n                    android:id=\"@+id/tv_compressed_size\"\n                    android:layout_width=\"wrap_content\"\n                    android:layout_height=\"wrap_content\"\n                    android:layout_marginTop=\"4dp\"\n                    tools:text=\"大小: 500 KB\" />\n\n                <TextView\n                    android:id=\"@+id/tv_compressed_dimens\"\n                    android:layout_width=\"wrap_content\"\n                    android:layout_height=\"wrap_content\"\n                    tools:text=\"尺寸: 1920 x 1080\" />\n            </LinearLayout>\n        </LinearLayout>\n\n    </LinearLayout>\n</ScrollView>"
  },
  {
    "path": "app-java/src/main/res/mipmap-anydpi/ic_launcher.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<adaptive-icon xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <background android:drawable=\"@drawable/ic_launcher_background\" />\n    <foreground android:drawable=\"@drawable/ic_launcher_foreground\" />\n    <monochrome android:drawable=\"@drawable/ic_launcher_foreground\" />\n</adaptive-icon>"
  },
  {
    "path": "app-java/src/main/res/mipmap-anydpi/ic_launcher_round.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<adaptive-icon xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <background android:drawable=\"@drawable/ic_launcher_background\" />\n    <foreground android:drawable=\"@drawable/ic_launcher_foreground\" />\n    <monochrome android:drawable=\"@drawable/ic_launcher_foreground\" />\n</adaptive-icon>"
  },
  {
    "path": "app-java/src/main/res/values/colors.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <color name=\"purple_200\">#FFBB86FC</color>\n    <color name=\"purple_500\">#FF6200EE</color>\n    <color name=\"purple_700\">#FF3700B3</color>\n    <color name=\"teal_200\">#FF03DAC5</color>\n    <color name=\"teal_700\">#FF018786</color>\n    <color name=\"black\">#FF000000</color>\n    <color name=\"white\">#FFFFFFFF</color>\n</resources>"
  },
  {
    "path": "app-java/src/main/res/values/strings.xml",
    "content": "<resources>\n    <string name=\"app_name\">Luban Java Sample</string>\n    <string name=\"select_image\">选择图片</string>\n    <string name=\"compress_image\">压缩图片</string>\n    <string name=\"original_image\">原图</string>\n    <string name=\"compressed_image\">压缩后</string>\n    <string name=\"file_size\">大小: %s</string>\n    <string name=\"image_size\">尺寸: %d x %d</string>\n    <string name=\"compress_success\">压缩成功</string>\n    <string name=\"compress_failed\">压缩失败: %s</string>\n    <string name=\"batch_compress\">批量压缩</string>\n    <string name=\"batch_compress_result\">批量压缩完成: 总计 %d, 成功 %d, 失败 %d</string>\n</resources>"
  },
  {
    "path": "app-java/src/main/res/values/themes.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n\n    <style name=\"Theme.Luban\" parent=\"Theme.MaterialComponents.DayNight.DarkActionBar\">\n        <!-- Primary brand color. -->\n        <item name=\"colorPrimary\">@color/purple_500</item>\n        <item name=\"colorPrimaryVariant\">@color/purple_700</item>\n        <item name=\"colorOnPrimary\">@color/white</item>\n        <!-- Secondary brand color. -->\n        <item name=\"colorSecondary\">@color/teal_200</item>\n        <item name=\"colorSecondaryVariant\">@color/teal_700</item>\n        <item name=\"colorOnSecondary\">@color/black</item>\n        <!-- Status bar color. -->\n        <item name=\"android:statusBarColor\">?attr/colorPrimaryVariant</item>\n        <!-- Customize your theme here. -->\n    </style>\n</resources>"
  },
  {
    "path": "app-java/src/main/res/values-night/themes.xml",
    "content": "<resources xmlns:tools=\"http://schemas.android.com/tools\">\n    <!-- Base application theme. -->\n    <style name=\"Theme.KotlinLuban\" parent=\"Theme.MaterialComponents.DayNight.DarkActionBar\">\n        <!-- Primary brand color. -->\n        <item name=\"colorPrimary\">@color/purple_200</item>\n        <item name=\"colorPrimaryVariant\">@color/purple_700</item>\n        <item name=\"colorOnPrimary\">@color/black</item>\n        <!-- Secondary brand color. -->\n        <item name=\"colorSecondary\">@color/teal_200</item>\n        <item name=\"colorSecondaryVariant\">@color/teal_200</item>\n        <item name=\"colorOnSecondary\">@color/black</item>\n        <!-- Status bar color. -->\n        <item name=\"android:statusBarColor\">?attr/colorPrimaryVariant</item>\n        <!-- Customize your theme here. -->\n    </style>\n</resources>"
  },
  {
    "path": "app-java/src/main/res/xml/backup_rules.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<full-backup-content>\n</full-backup-content>"
  },
  {
    "path": "app-java/src/main/res/xml/data_extraction_rules.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<data-extraction-rules>\n    <cloud-backup>\n    </cloud-backup>\n</data-extraction-rules>"
  },
  {
    "path": "app-java/src/test/java/top/zibin/luban/app/java/ExampleUnitTest.java",
    "content": "package top.zibin.luban.app.java;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Example local unit test, which will execute on the development machine (host).\n *\n * @see <a href=\"http://d.android.com/tools/testing\">Testing documentation</a>\n */\npublic class ExampleUnitTest {\n    @Test\n    public void addition_isCorrect() {\n        assertEquals(4, 2 + 2);\n    }\n}"
  },
  {
    "path": "build.gradle.kts",
    "content": "plugins {\n    alias(libs.plugins.android.application) apply false\n    alias(libs.plugins.kotlin.android) apply false\n    alias(libs.plugins.kotlin.compose) apply false\n    alias(libs.plugins.android.library) apply false\n    alias(libs.plugins.maven.publish) apply false\n}"
  },
  {
    "path": "gradle/libs.versions.toml",
    "content": "[versions]\nagp = \"9.0.0\"\nkotlin = \"2.3.0\"\ncoreKtx = \"1.17.0\"\njunit = \"4.13.2\"\njunitVersion = \"1.3.0\"\nespressoCore = \"3.7.0\"\nlifecycleRuntimeKtx = \"2.10.0\"\nactivityCompose = \"1.12.2\"\ncomposeBom = \"2025.12.01\"\ncoroutines = \"1.10.2\"\nexifinterface = \"1.4.2\"\nappcompat = \"1.7.1\"\nmaterial = \"1.13.0\"\ncoil = \"2.7.0\"\nmavenPublish = \"0.35.0\"\n\n[libraries]\nandroidx-core-ktx = { group = \"androidx.core\", name = \"core-ktx\", version.ref = \"coreKtx\" }\njunit = { group = \"junit\", name = \"junit\", version.ref = \"junit\" }\nandroidx-junit = { group = \"androidx.test.ext\", name = \"junit\", version.ref = \"junitVersion\" }\nandroidx-espresso-core = { group = \"androidx.test.espresso\", name = \"espresso-core\", version.ref = \"espressoCore\" }\nandroidx-lifecycle-runtime-ktx = { group = \"androidx.lifecycle\", name = \"lifecycle-runtime-ktx\", version.ref = \"lifecycleRuntimeKtx\" }\nandroidx-activity-compose = { group = \"androidx.activity\", name = \"activity-compose\", version.ref = \"activityCompose\" }\nandroidx-compose-bom = { group = \"androidx.compose\", name = \"compose-bom\", version.ref = \"composeBom\" }\nandroidx-compose-ui = { group = \"androidx.compose.ui\", name = \"ui\" }\nandroidx-compose-ui-graphics = { group = \"androidx.compose.ui\", name = \"ui-graphics\" }\nandroidx-compose-ui-tooling = { group = \"androidx.compose.ui\", name = \"ui-tooling\" }\nandroidx-compose-ui-tooling-preview = { group = \"androidx.compose.ui\", name = \"ui-tooling-preview\" }\nandroidx-compose-ui-test-manifest = { group = \"androidx.compose.ui\", name = \"ui-test-manifest\" }\nandroidx-compose-ui-test-junit4 = { group = \"androidx.compose.ui\", name = \"ui-test-junit4\" }\nandroidx-compose-material3 = { group = \"androidx.compose.material3\", name = \"material3\" }\nandroidx-compose-material-icons-extended = { group = \"androidx.compose.material\", name = \"material-icons-extended\" }\nandroidx-appcompat = { group = \"androidx.appcompat\", name = \"appcompat\", version.ref = \"appcompat\" }\nmaterial = { group = \"com.google.android.material\", name = \"material\", version.ref = \"material\" }\nkotlinx-coroutines-android = { group = \"org.jetbrains.kotlinx\", name = \"kotlinx-coroutines-android\", version.ref = \"coroutines\" }\nkotlinx-coroutines-core = { group = \"org.jetbrains.kotlinx\", name = \"kotlinx-coroutines-core\", version.ref = \"coroutines\" }\nandroidx-exifinterface = { group = \"androidx.exifinterface\", name = \"exifinterface\", version.ref = \"exifinterface\" }\ncoil-compose = { group = \"io.coil-kt\", name = \"coil-compose\", version.ref = \"coil\" }\n\n[plugins]\nandroid-application = { id = \"com.android.application\", version.ref = \"agp\" }\nkotlin-android = { id = \"org.jetbrains.kotlin.android\", version.ref = \"kotlin\" }\nkotlin-compose = { id = \"org.jetbrains.kotlin.plugin.compose\", version.ref = \"kotlin\" }\nandroid-library = { id = \"com.android.library\", version.ref = \"agp\" }\nmaven-publish = { id = \"com.vanniktech.maven.publish\", version.ref = \"mavenPublish\" }\n"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "content": "#Mon Jan 05 11:56:32 CST 2026\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-9.3.0-bin.zip\nnetworkTimeout=10000\nvalidateDistributionUrl=true\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\n"
  },
  {
    "path": "gradle.properties",
    "content": "# Project-wide Gradle settings.\n# IDE (e.g. Android Studio) users:\n# Gradle settings configured through the IDE *will override*\n# any settings specified in this file.\n# For more details on how to configure your build environment visit\n# http://www.gradle.org/docs/current/userguide/build_environment.html\n# Specifies the JVM arguments used for the daemon process.\n# The setting is particularly useful for tweaking memory settings.\norg.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8\n# When configured, Gradle will run in incubating parallel mode.\n# This option should only be used with decoupled projects. For more details, visit\n# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects\n# org.gradle.parallel=true\n# AndroidX package structure to make it clearer which packages are bundled with the\n# Android operating system, and which are packaged with your app's APK\n# https://developer.android.com/topic/libraries/support-library/androidx-rn\nandroid.useAndroidX=true\n# Kotlin code style for this project: \"official\" or \"obsolete\":\nkotlin.code.style=official\n# Enables namespacing of each library's R class so that its R class includes only the\n# resources declared in the library itself and none from the library's dependencies,\n# thereby reducing the size of the R class for that library\nandroid.nonTransitiveRClass=true\n\nandroid.defaults.buildfeatures.resvalues=true\nandroid.sdk.defaultTargetSdkToCompileSdkIfUnset=false\nandroid.enableAppCompileTimeRClass=false\nandroid.usesSdkInManifest.disallowed=false\nandroid.uniquePackageNames=false\nandroid.dependency.useConstraints=true\nandroid.r8.strictFullModeForKeepRules=false\nandroid.r8.optimizedResourceShrinking=false\nandroid.builtInKotlin=false\nandroid.newDsl=false"
  },
  {
    "path": "gradlew",
    "content": "#!/bin/sh\n\n#\n# Copyright © 2015 the original authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# SPDX-License-Identifier: Apache-2.0\n#\n\n##############################################################################\n#\n#   Gradle start up script for POSIX generated by Gradle.\n#\n#   Important for running:\n#\n#   (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is\n#       noncompliant, but you have some other compliant shell such as ksh or\n#       bash, then to run this script, type that shell name before the whole\n#       command line, like:\n#\n#           ksh Gradle\n#\n#       Busybox and similar reduced shells will NOT work, because this script\n#       requires all of these POSIX shell features:\n#         * functions;\n#         * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,\n#           «${var#prefix}», «${var%suffix}», and «$( cmd )»;\n#         * compound commands having a testable exit status, especially «case»;\n#         * various built-in commands including «command», «set», and «ulimit».\n#\n#   Important for patching:\n#\n#   (2) This script targets any POSIX shell, so it avoids extensions provided\n#       by Bash, Ksh, etc; in particular arrays are avoided.\n#\n#       The \"traditional\" practice of packing multiple parameters into a\n#       space-separated string is a well documented source of bugs and security\n#       problems, so this is (mostly) avoided, by progressively accumulating\n#       options in \"$@\", and eventually passing that to Java.\n#\n#       Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,\n#       and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;\n#       see the in-line comments for details.\n#\n#       There are tweaks for specific operating systems such as AIX, CygWin,\n#       Darwin, MinGW, and NonStop.\n#\n#   (3) This script is generated from the Groovy template\n#       https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt\n#       within the Gradle project.\n#\n#       You can find Gradle at https://github.com/gradle/gradle/.\n#\n##############################################################################\n\n# Attempt to set APP_HOME\n\n# Resolve links: $0 may be a link\napp_path=$0\n\n# Need this for daisy-chained symlinks.\nwhile\n    APP_HOME=${app_path%\"${app_path##*/}\"}  # leaves a trailing /; empty if no leading path\n    [ -h \"$app_path\" ]\ndo\n    ls=$( ls -ld \"$app_path\" )\n    link=${ls#*' -> '}\n    case $link in             #(\n      /*)   app_path=$link ;; #(\n      *)    app_path=$APP_HOME$link ;;\n    esac\ndone\n\n# This is normally unused\n# shellcheck disable=SC2034\nAPP_BASE_NAME=${0##*/}\n# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)\nAPP_HOME=$( cd -P \"${APP_HOME:-./}\" > /dev/null && printf '%s\\n' \"$PWD\" ) || exit\n\n# Use the maximum available, or set MAX_FD != -1 to use that value.\nMAX_FD=maximum\n\nwarn () {\n    echo \"$*\"\n} >&2\n\ndie () {\n    echo\n    echo \"$*\"\n    echo\n    exit 1\n} >&2\n\n# OS specific support (must be 'true' or 'false').\ncygwin=false\nmsys=false\ndarwin=false\nnonstop=false\ncase \"$( uname )\" in                #(\n  CYGWIN* )         cygwin=true  ;; #(\n  Darwin* )         darwin=true  ;; #(\n  MSYS* | MINGW* )  msys=true    ;; #(\n  NONSTOP* )        nonstop=true ;;\nesac\n\nCLASSPATH=\"\\\\\\\"\\\\\\\"\"\n\n\n# Determine the Java command to use to start the JVM.\nif [ -n \"$JAVA_HOME\" ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n        # IBM's JDK on AIX uses strange locations for the executables\n        JAVACMD=$JAVA_HOME/jre/sh/java\n    else\n        JAVACMD=$JAVA_HOME/bin/java\n    fi\n    if [ ! -x \"$JAVACMD\" ] ; then\n        die \"ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nelse\n    JAVACMD=java\n    if ! command -v java >/dev/null 2>&1\n    then\n        die \"ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nfi\n\n# Increase the maximum file descriptors if we can.\nif ! \"$cygwin\" && ! \"$darwin\" && ! \"$nonstop\" ; then\n    case $MAX_FD in #(\n      max*)\n        # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.\n        # shellcheck disable=SC2039,SC3045\n        MAX_FD=$( ulimit -H -n ) ||\n            warn \"Could not query maximum file descriptor limit\"\n    esac\n    case $MAX_FD in  #(\n      '' | soft) :;; #(\n      *)\n        # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.\n        # shellcheck disable=SC2039,SC3045\n        ulimit -n \"$MAX_FD\" ||\n            warn \"Could not set maximum file descriptor limit to $MAX_FD\"\n    esac\nfi\n\n# Collect all arguments for the java command, stacking in reverse order:\n#   * args from the command line\n#   * the main class name\n#   * -classpath\n#   * -D...appname settings\n#   * --module-path (only if needed)\n#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.\n\n# For Cygwin or MSYS, switch paths to Windows format before running java\nif \"$cygwin\" || \"$msys\" ; then\n    APP_HOME=$( cygpath --path --mixed \"$APP_HOME\" )\n    CLASSPATH=$( cygpath --path --mixed \"$CLASSPATH\" )\n\n    JAVACMD=$( cygpath --unix \"$JAVACMD\" )\n\n    # Now convert the arguments - kludge to limit ourselves to /bin/sh\n    for arg do\n        if\n            case $arg in                                #(\n              -*)   false ;;                            # don't mess with options #(\n              /?*)  t=${arg#/} t=/${t%%/*}              # looks like a POSIX filepath\n                    [ -e \"$t\" ] ;;                      #(\n              *)    false ;;\n            esac\n        then\n            arg=$( cygpath --path --ignore --mixed \"$arg\" )\n        fi\n        # Roll the args list around exactly as many times as the number of\n        # args, so each arg winds up back in the position where it started, but\n        # possibly modified.\n        #\n        # NB: a `for` loop captures its iteration list before it begins, so\n        # changing the positional parameters here affects neither the number of\n        # iterations, nor the values presented in `arg`.\n        shift                   # remove old arg\n        set -- \"$@\" \"$arg\"      # push replacement arg\n    done\nfi\n\n\n# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nDEFAULT_JVM_OPTS='\"-Xmx64m\" \"-Xms64m\"'\n\n# Collect all arguments for the java command:\n#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,\n#     and any embedded shellness will be escaped.\n#   * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be\n#     treated as '${Hostname}' itself on the command line.\n\nset -- \\\n        \"-Dorg.gradle.appname=$APP_BASE_NAME\" \\\n        -classpath \"$CLASSPATH\" \\\n        -jar \"$APP_HOME/gradle/wrapper/gradle-wrapper.jar\" \\\n        \"$@\"\n\n# Stop when \"xargs\" is not available.\nif ! command -v xargs >/dev/null 2>&1\nthen\n    die \"xargs is not available\"\nfi\n\n# Use \"xargs\" to parse quoted args.\n#\n# With -n1 it outputs one arg per line, with the quotes and backslashes removed.\n#\n# In Bash we could simply go:\n#\n#   readarray ARGS < <( xargs -n1 <<<\"$var\" ) &&\n#   set -- \"${ARGS[@]}\" \"$@\"\n#\n# but POSIX shell has neither arrays nor command substitution, so instead we\n# post-process each arg (as a line of input to sed) to backslash-escape any\n# character that might be a shell metacharacter, then use eval to reverse\n# that process (while maintaining the separation between arguments), and wrap\n# the whole thing up as a single \"set\" statement.\n#\n# This will of course break if any of these variables contains a newline or\n# an unmatched quote.\n#\n\neval \"set -- $(\n        printf '%s\\n' \"$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS\" |\n        xargs -n1 |\n        sed ' s~[^-[:alnum:]+,./:=@_]~\\\\&~g; ' |\n        tr '\\n' ' '\n    )\" '\"$@\"'\n\nexec \"$JAVACMD\" \"$@\"\n"
  },
  {
    "path": "gradlew.bat",
    "content": "@rem\r\n@rem Copyright 2015 the original author or authors.\r\n@rem\r\n@rem Licensed under the Apache License, Version 2.0 (the \"License\");\r\n@rem you may not use this file except in compliance with the License.\r\n@rem You may obtain a copy of the License at\r\n@rem\r\n@rem      https://www.apache.org/licenses/LICENSE-2.0\r\n@rem\r\n@rem Unless required by applicable law or agreed to in writing, software\r\n@rem distributed under the License is distributed on an \"AS IS\" BASIS,\r\n@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n@rem See the License for the specific language governing permissions and\r\n@rem limitations under the License.\r\n@rem\r\n@rem SPDX-License-Identifier: Apache-2.0\r\n@rem\r\n\r\n@if \"%DEBUG%\"==\"\" @echo off\r\n@rem ##########################################################################\r\n@rem\r\n@rem  Gradle startup script for Windows\r\n@rem\r\n@rem ##########################################################################\r\n\r\n@rem Set local scope for the variables with windows NT shell\r\nif \"%OS%\"==\"Windows_NT\" setlocal\r\n\r\nset DIRNAME=%~dp0\r\nif \"%DIRNAME%\"==\"\" set DIRNAME=.\r\n@rem This is normally unused\r\nset APP_BASE_NAME=%~n0\r\nset APP_HOME=%DIRNAME%\r\n\r\n@rem Resolve any \".\" and \"..\" in APP_HOME to make it shorter.\r\nfor %%i in (\"%APP_HOME%\") do set APP_HOME=%%~fi\r\n\r\n@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\r\nset DEFAULT_JVM_OPTS=\"-Xmx64m\" \"-Xms64m\"\r\n\r\n@rem Find java.exe\r\nif defined JAVA_HOME goto findJavaFromJavaHome\r\n\r\nset JAVA_EXE=java.exe\r\n%JAVA_EXE% -version >NUL 2>&1\r\nif %ERRORLEVEL% equ 0 goto execute\r\n\r\necho. 1>&2\r\necho ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2\r\necho. 1>&2\r\necho Please set the JAVA_HOME variable in your environment to match the 1>&2\r\necho location of your Java installation. 1>&2\r\n\r\ngoto fail\r\n\r\n:findJavaFromJavaHome\r\nset JAVA_HOME=%JAVA_HOME:\"=%\r\nset JAVA_EXE=%JAVA_HOME%/bin/java.exe\r\n\r\nif exist \"%JAVA_EXE%\" goto execute\r\n\r\necho. 1>&2\r\necho ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2\r\necho. 1>&2\r\necho Please set the JAVA_HOME variable in your environment to match the 1>&2\r\necho location of your Java installation. 1>&2\r\n\r\ngoto fail\r\n\r\n:execute\r\n@rem Setup the command line\r\n\r\nset CLASSPATH=\r\n\r\n\r\n@rem Execute Gradle\r\n\"%JAVA_EXE%\" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% \"-Dorg.gradle.appname=%APP_BASE_NAME%\" -classpath \"%CLASSPATH%\" -jar \"%APP_HOME%\\gradle\\wrapper\\gradle-wrapper.jar\" %*\r\n\r\n:end\r\n@rem End local scope for the variables with windows NT shell\r\nif %ERRORLEVEL% equ 0 goto mainEnd\r\n\r\n:fail\r\nrem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\r\nrem the _cmd.exe /c_ return code!\r\nset EXIT_CODE=%ERRORLEVEL%\r\nif %EXIT_CODE% equ 0 set EXIT_CODE=1\r\nif not \"\"==\"%GRADLE_EXIT_CONSOLE%\" exit %EXIT_CODE%\r\nexit /b %EXIT_CODE%\r\n\r\n:mainEnd\r\nif \"%OS%\"==\"Windows_NT\" endlocal\r\n\r\n:omega\r\n"
  },
  {
    "path": "luban/.gitignore",
    "content": "/build"
  },
  {
    "path": "luban/build.gradle.kts",
    "content": "@file:Suppress(\"UnstableApiUsage\")\n\nplugins {\n    alias(libs.plugins.android.library)\n    alias(libs.plugins.kotlin.android)\n    alias(libs.plugins.maven.publish)\n}\n\nval libraryVersion = \"2.0.1\"\n\nandroid {\n    namespace = \"top.zibin.luban\"\n    compileSdk = 36\n\n    defaultConfig {\n        minSdk = 21\n        testInstrumentationRunner = \"androidx.test.runner.AndroidJUnitRunner\"\n        consumerProguardFiles(\"consumer-rules.pro\")\n\n        ndk {\n            abiFilters += listOf(\"armeabi-v7a\", \"arm64-v8a\", \"x86\", \"x86_64\")\n        }\n\n        externalNativeBuild {\n            cmake {\n                cppFlags += \"-std=c++17\"\n                arguments += listOf(\"-DANDROID_STL=c++_static\", \"-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON\")\n            }\n        }\n    }\n\n    buildTypes {\n        release {\n            isMinifyEnabled = false\n            proguardFiles(\n                getDefaultProguardFile(\"proguard-android-optimize.txt\"),\n                \"proguard-rules.pro\"\n            )\n        }\n    }\n    compileOptions {\n        sourceCompatibility = JavaVersion.VERSION_17\n        targetCompatibility = JavaVersion.VERSION_17\n    }\n    kotlin {\n        compilerOptions {\n            jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)\n        }\n    }\n\n    externalNativeBuild {\n        cmake {\n            path = file(\"src/main/cpp/CMakeLists.txt\")\n            version = \"3.22.1\"\n        }\n    }\n\n    packaging {\n        jniLibs {\n            useLegacyPackaging = true\n            excludes += \"lib/**/libc++_shared.so\"\n        }\n    }\n}\n\ndependencies {\n    api(libs.kotlinx.coroutines.android)\n    api(libs.kotlinx.coroutines.core)\n    implementation(libs.androidx.core.ktx)\n    implementation(libs.androidx.appcompat)\n    implementation(libs.material)\n    implementation(libs.androidx.exifinterface)\n    testImplementation(libs.junit)\n    androidTestImplementation(libs.androidx.junit)\n    androidTestImplementation(libs.androidx.espresso.core)\n}\n\nmavenPublishing {\n    publishToMavenCentral()\n\n    signAllPublications()\n\n    coordinates(\"top.zibin\", \"luban\", libraryVersion)\n\n    pom {\n        name.set(\"Luban\")\n        description.set(\"Luban（鲁班） —— Android图片压缩工具，仿微信朋友圈压缩策略。\")\n        url.set(\"https://github.com/Curzibn/Luban\")\n\n        licenses {\n            license {\n                name.set(\"The Apache License, Version 2.0\")\n                url.set(\"http://www.apache.org/licenses/LICENSE-2.0.txt\")\n                distribution.set(\"http://www.apache.org/licenses/LICENSE-2.0.txt\")\n            }\n        }\n\n        developers {\n            developer {\n                id.set(\"Curzibn\")\n                name.set(\"Zibin Zheng\")\n                email.set(\"a@zibin.top\")\n            }\n        }\n\n        scm {\n            connection.set(\"scm:git:git://github.com/Curzibn/Luban.git\")\n            developerConnection.set(\"scm:git:ssh://git@github.com/Curzibn/Luban.git\")\n            url.set(\"https://github.com/Curzibn/Luban\")\n        }\n    }\n}"
  },
  {
    "path": "luban/consumer-rules.pro",
    "content": "-keep class top.zibin.luban.compression.TurboJpegNative {\n    native <methods>;\n}\n"
  },
  {
    "path": "luban/proguard-rules.pro",
    "content": "# Add project specific ProGuard rules here.\n# You can control the set of applied configuration files using the\n# proguardFiles setting in build.gradle.\n#\n# For more details, see\n#   http://developer.android.com/guide/developing/tools/proguard.html\n\n# If your project uses WebView with JS, uncomment the following\n# and specify the fully qualified class name to the JavaScript interface\n# class:\n#-keepclassmembers class fqcn.of.javascript.interface.for.webview {\n#   public *;\n#}\n\n# Uncomment this to preserve the line number information for\n# debugging stack traces.\n#-keepattributes SourceFile,LineNumberTable\n\n# If you keep the line number information, uncomment this to\n# hide the original source file name.\n#-renamesourcefileattribute SourceFile"
  },
  {
    "path": "luban/src/androidTest/java/top/zibin/luban/ExampleInstrumentedTest.kt",
    "content": "package top.zibin.luban\n\nimport androidx.test.platform.app.InstrumentationRegistry\nimport androidx.test.ext.junit.runners.AndroidJUnit4\n\nimport org.junit.Test\nimport org.junit.runner.RunWith\n\nimport org.junit.Assert.*\n\n/**\n * 在 Android 设备上执行的仪器测试。\n *\n * 参见 [测试文档](http://d.android.com/tools/testing)。\n *\n * Instrumented test, which will execute on an Android device.\n *\n * See [testing documentation](http://d.android.com/tools/testing).\n */\n@RunWith(AndroidJUnit4::class)\nclass ExampleInstrumentedTest {\n    @Test\n    fun useAppContext() {\n        val appContext = InstrumentationRegistry.getInstrumentation().targetContext\n        assertEquals(\"top.zibin.luban.test\", appContext.packageName)\n    }\n}"
  },
  {
    "path": "luban/src/main/AndroidManifest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n</manifest>"
  },
  {
    "path": "luban/src/main/cpp/CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.22.1)\n\nproject(turbojpeg-wrapper)\n\nset(CMAKE_CXX_STANDARD 17)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\n\nset(jniLibsDir \"${CMAKE_SOURCE_DIR}/../jniLibs\")\n\nadd_library(turbojpeg SHARED IMPORTED)\nset_target_properties(turbojpeg PROPERTIES\n    IMPORTED_LOCATION \"${jniLibsDir}/${ANDROID_ABI}/libturbojpeg.so\"\n)\n\nadd_library(turbojpeg-wrapper SHARED\n    turbojpeg_wrapper.cpp\n)\n\ntarget_include_directories(turbojpeg-wrapper PRIVATE\n    ${CMAKE_CURRENT_SOURCE_DIR}\n)\n\nfind_library(log-lib log)\n\ntarget_link_libraries(turbojpeg-wrapper\n    turbojpeg\n    ${log-lib}\n    android\n)\n"
  },
  {
    "path": "luban/src/main/cpp/turbojpeg.h",
    "content": "/*\n * Copyright (C)2009-2015, 2017, 2020-2025 D. R. Commander.\n *                                         All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n *   this list of conditions and the following disclaimer.\n * - Redistributions in binary form must reproduce the above copyright notice,\n *   this list of conditions and the following disclaimer in the documentation\n *   and/or other materials provided with the distribution.\n * - Neither the name of the libjpeg-turbo Project nor the names of its\n *   contributors may be used to endorse or promote products derived from this\n *   software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\",\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef __TURBOJPEG_H__\n#define __TURBOJPEG_H__\n\n#include <stddef.h>\n\n#if defined(_WIN32) && defined(DLLDEFINE)\n#define DLLEXPORT  __declspec(dllexport)\n#else\n#define DLLEXPORT\n#endif\n#define DLLCALL\n\n\n/**\n * @addtogroup TurboJPEG\n * TurboJPEG API.  This API provides an interface for generating, decoding, and\n * transforming planar YUV and JPEG images in memory.\n *\n * @anchor YUVnotes\n * YUV Image Format Notes\n * ----------------------\n * Technically, the JPEG format uses the YCbCr colorspace (which is technically\n * not a colorspace but a color transform), but per the convention of the\n * digital video community, the TurboJPEG API uses \"YUV\" to refer to an image\n * format consisting of Y, Cb, and Cr image planes.\n *\n * Each plane is simply a 2D array of bytes, each byte representing the value\n * of one of the components (Y, Cb, or Cr) at a particular location in the\n * image.  The width and height of each plane are determined by the image\n * width, height, and level of chrominance subsampling.  The luminance plane\n * width is the image width padded to the nearest multiple of the horizontal\n * subsampling factor (1 in the case of 4:4:4, grayscale, 4:4:0, or 4:4:1; 2 in\n * the case of 4:2:2 or 4:2:0; 4 in the case of 4:1:1.)  Similarly, the\n * luminance plane height is the image height padded to the nearest multiple of\n * the vertical subsampling factor (1 in the case of 4:4:4, 4:2:2, grayscale,\n * or 4:1:1; 2 in the case of 4:2:0 or 4:4:0; 4 in the case of 4:4:1.)  This is\n * irrespective of any additional padding that may be specified as an argument\n * to the various YUV functions.  The chrominance plane width is equal to the\n * luminance plane width divided by the horizontal subsampling factor, and the\n * chrominance plane height is equal to the luminance plane height divided by\n * the vertical subsampling factor.\n *\n * For example, if the source image is 35 x 35 pixels and 4:2:2 subsampling is\n * used, then the luminance plane would be 36 x 35 bytes, and each of the\n * chrominance planes would be 18 x 35 bytes.  If you specify a row alignment\n * of 4 bytes on top of this, then the luminance plane would be 36 x 35 bytes,\n * and each of the chrominance planes would be 20 x 35 bytes.\n *\n * @{\n */\n\n\n/**\n * The number of initialization options\n */\n#define TJ_NUMINIT  3\n\n/**\n * Initialization options\n */\nenum TJINIT {\n  /**\n   * Initialize the TurboJPEG instance for compression.\n   */\n  TJINIT_COMPRESS,\n  /**\n   * Initialize the TurboJPEG instance for decompression.\n   */\n  TJINIT_DECOMPRESS,\n  /**\n   * Initialize the TurboJPEG instance for lossless transformation (both\n   * compression and decompression.)\n   */\n  TJINIT_TRANSFORM\n};\n\n\n/**\n * The number of chrominance subsampling options\n */\n#define TJ_NUMSAMP  7\n\n/**\n * Chrominance subsampling options\n *\n * When pixels are converted from RGB to YCbCr (see #TJCS_YCbCr) or from CMYK\n * to YCCK (see #TJCS_YCCK) as part of the JPEG compression process, some of\n * the Cb and Cr (chrominance) components can be discarded or averaged together\n * to produce a smaller image with little perceptible loss of image quality.\n * (The human eye is more sensitive to small changes in brightness than to\n * small changes in color.)  This is called \"chrominance subsampling\".\n */\nenum TJSAMP {\n  /**\n   * 4:4:4 chrominance subsampling (no chrominance subsampling)\n   *\n   * The JPEG or YUV image will contain one chrominance component for every\n   * pixel in the source image.\n   */\n  TJSAMP_444,\n  /**\n   * 4:2:2 chrominance subsampling\n   *\n   * The JPEG or YUV image will contain one chrominance component for every 2x1\n   * block of pixels in the source image.\n   */\n  TJSAMP_422,\n  /**\n   * 4:2:0 chrominance subsampling\n   *\n   * The JPEG or YUV image will contain one chrominance component for every 2x2\n   * block of pixels in the source image.\n   */\n  TJSAMP_420,\n  /**\n   * Grayscale\n   *\n   * The JPEG or YUV image will contain no chrominance components.\n   */\n  TJSAMP_GRAY,\n  /**\n   * 4:4:0 chrominance subsampling\n   *\n   * The JPEG or YUV image will contain one chrominance component for every 1x2\n   * block of pixels in the source image.\n   *\n   * @note 4:4:0 subsampling is not fully accelerated in libjpeg-turbo.\n   */\n  TJSAMP_440,\n  /**\n   * 4:1:1 chrominance subsampling\n   *\n   * The JPEG or YUV image will contain one chrominance component for every 4x1\n   * block of pixels in the source image.  All else being equal, a JPEG image\n   * with 4:1:1 subsampling is almost exactly the same size as a JPEG image\n   * with 4:2:0 subsampling, and in the aggregate, both subsampling methods\n   * produce approximately the same perceptual quality.  However, 4:1:1 is\n   * better able to reproduce sharp horizontal features.\n   *\n   * @note 4:1:1 subsampling is not fully accelerated in libjpeg-turbo.\n   */\n  TJSAMP_411,\n  /**\n   * 4:4:1 chrominance subsampling\n   *\n   * The JPEG or YUV image will contain one chrominance component for every 1x4\n   * block of pixels in the source image.  All else being equal, a JPEG image\n   * with 4:4:1 subsampling is almost exactly the same size as a JPEG image\n   * with 4:2:0 subsampling, and in the aggregate, both subsampling methods\n   * produce approximately the same perceptual quality.  However, 4:4:1 is\n   * better able to reproduce sharp vertical features.\n   *\n   * @note 4:4:1 subsampling is not fully accelerated in libjpeg-turbo.\n   */\n  TJSAMP_441,\n  /**\n   * Unknown subsampling\n   *\n   * The JPEG image uses an unusual type of chrominance subsampling.  Such\n   * images can be decompressed into packed-pixel images, but they cannot be\n   * - decompressed into planar YUV images,\n   * - losslessly transformed if #TJXOPT_CROP is specified and #TJXOPT_GRAY is\n   * not specified, or\n   * - partially decompressed using a cropping region.\n   */\n  TJSAMP_UNKNOWN = -1\n};\n\n/**\n * iMCU width (in pixels) for a given level of chrominance subsampling\n *\n * In a typical lossy JPEG image, 8x8 blocks of DCT coefficients for each\n * component are interleaved in a single scan.  If the image uses chrominance\n * subsampling, then multiple luminance blocks are stored together, followed by\n * a single block for each chrominance component.  The minimum set of\n * full-resolution luminance block(s) and corresponding (possibly subsampled)\n * chrominance blocks necessary to represent at least one DCT block per\n * component is called a \"Minimum Coded Unit\" or \"MCU\".  (For example, an MCU\n * in an interleaved lossy JPEG image that uses 4:2:2 subsampling consists of\n * two luminance blocks followed by one block for each chrominance component.)\n * In a non-interleaved lossy JPEG image, each component is stored in a\n * separate scan, and an MCU is a single DCT block, so we use the term \"iMCU\"\n * (interleaved MCU) to refer to the equivalent of an MCU in an interleaved\n * JPEG image.  For the common case of interleaved JPEG images, an iMCU is the\n * same as an MCU.\n *\n * iMCU sizes:\n * - 8x8 for no subsampling or grayscale\n * - 16x8 for 4:2:2\n * - 8x16 for 4:4:0\n * - 16x16 for 4:2:0\n * - 32x8 for 4:1:1\n * - 8x32 for 4:4:1\n */\nstatic const int tjMCUWidth[TJ_NUMSAMP]  = { 8, 16, 16, 8, 8, 32, 8 };\n\n/**\n * iMCU height (in pixels) for a given level of chrominance subsampling\n *\n * In a typical lossy JPEG image, 8x8 blocks of DCT coefficients for each\n * component are interleaved in a single scan.  If the image uses chrominance\n * subsampling, then multiple luminance blocks are stored together, followed by\n * a single block for each chrominance component.  The minimum set of\n * full-resolution luminance block(s) and corresponding (possibly subsampled)\n * chrominance blocks necessary to represent at least one DCT block per\n * component is called a \"Minimum Coded Unit\" or \"MCU\".  (For example, an MCU\n * in an interleaved lossy JPEG image that uses 4:2:2 subsampling consists of\n * two luminance blocks followed by one block for each chrominance component.)\n * In a non-interleaved lossy JPEG image, each component is stored in a\n * separate scan, and an MCU is a single DCT block, so we use the term \"iMCU\"\n * (interleaved MCU) to refer to the equivalent of an MCU in an interleaved\n * JPEG image.  For the common case of interleaved JPEG images, an iMCU is the\n * same as an MCU.\n *\n * iMCU sizes:\n * - 8x8 for no subsampling or grayscale\n * - 16x8 for 4:2:2\n * - 8x16 for 4:4:0\n * - 16x16 for 4:2:0\n * - 32x8 for 4:1:1\n * - 8x32 for 4:4:1\n */\nstatic const int tjMCUHeight[TJ_NUMSAMP] = { 8, 8, 16, 8, 16, 8, 32 };\n\n\n/**\n * The number of pixel formats\n */\n#define TJ_NUMPF  12\n\n/**\n * Pixel formats\n */\nenum TJPF {\n  /**\n   * RGB pixel format\n   *\n   * The red, green, and blue components in the image are stored in 3-sample\n   * pixels in the order R, G, B from lowest to highest memory address within\n   * each pixel.\n   */\n  TJPF_RGB,\n  /**\n   * BGR pixel format\n   *\n   * The red, green, and blue components in the image are stored in 3-sample\n   * pixels in the order B, G, R from lowest to highest memory address within\n   * each pixel.\n   */\n  TJPF_BGR,\n  /**\n   * RGBX pixel format\n   *\n   * The red, green, and blue components in the image are stored in 4-sample\n   * pixels in the order R, G, B from lowest to highest memory address within\n   * each pixel.  The X component is ignored when compressing/encoding and\n   * undefined when decompressing/decoding.\n   */\n  TJPF_RGBX,\n  /**\n   * BGRX pixel format\n   *\n   * The red, green, and blue components in the image are stored in 4-sample\n   * pixels in the order B, G, R from lowest to highest memory address within\n   * each pixel.  The X component is ignored when compressing/encoding and\n   * undefined when decompressing/decoding.\n   */\n  TJPF_BGRX,\n  /**\n   * XBGR pixel format\n   *\n   * The red, green, and blue components in the image are stored in 4-sample\n   * pixels in the order R, G, B from highest to lowest memory address within\n   * each pixel.  The X component is ignored when compressing/encoding and\n   * undefined when decompressing/decoding.\n   */\n  TJPF_XBGR,\n  /**\n   * XRGB pixel format\n   *\n   * The red, green, and blue components in the image are stored in 4-sample\n   * pixels in the order B, G, R from highest to lowest memory address within\n   * each pixel.  The X component is ignored when compressing/encoding and\n   * undefined when decompressing/decoding.\n   */\n  TJPF_XRGB,\n  /**\n   * Grayscale pixel format\n   *\n   * Each 1-sample pixel represents a luminance (brightness) level from 0 to\n   * the maximum sample value (which is, for instance, 255 for 8-bit samples or\n   * 4095 for 12-bit samples or 65535 for 16-bit samples.)\n   */\n  TJPF_GRAY,\n  /**\n   * RGBA pixel format\n   *\n   * This is the same as @ref TJPF_RGBX, except that when\n   * decompressing/decoding, the X component is guaranteed to be equal to the\n   * maximum sample value, which can be interpreted as an opaque alpha channel.\n   */\n  TJPF_RGBA,\n  /**\n   * BGRA pixel format\n   *\n   * This is the same as @ref TJPF_BGRX, except that when\n   * decompressing/decoding, the X component is guaranteed to be equal to the\n   * maximum sample value, which can be interpreted as an opaque alpha channel.\n   */\n  TJPF_BGRA,\n  /**\n   * ABGR pixel format\n   *\n   * This is the same as @ref TJPF_XBGR, except that when\n   * decompressing/decoding, the X component is guaranteed to be equal to the\n   * maximum sample value, which can be interpreted as an opaque alpha channel.\n   */\n  TJPF_ABGR,\n  /**\n   * ARGB pixel format\n   *\n   * This is the same as @ref TJPF_XRGB, except that when\n   * decompressing/decoding, the X component is guaranteed to be equal to the\n   * maximum sample value, which can be interpreted as an opaque alpha channel.\n   */\n  TJPF_ARGB,\n  /**\n   * CMYK pixel format\n   *\n   * Unlike RGB, which is an additive color model used primarily for display,\n   * CMYK (Cyan/Magenta/Yellow/Key) is a subtractive color model used primarily\n   * for printing.  In the CMYK color model, the value of each color component\n   * typically corresponds to an amount of cyan, magenta, yellow, or black ink\n   * that is applied to a white background.  In order to convert between CMYK\n   * and RGB, it is necessary to use a color management system (CMS.)  A CMS\n   * will attempt to map colors within the printer's gamut to perceptually\n   * similar colors in the display's gamut and vice versa, but the mapping is\n   * typically not 1:1 or reversible, nor can it be defined with a simple\n   * formula.  Thus, such a conversion is out of scope for a codec library.\n   * However, the TurboJPEG API allows for compressing packed-pixel CMYK images\n   * into YCCK JPEG images (see #TJCS_YCCK) and decompressing YCCK JPEG images\n   * into packed-pixel CMYK images.\n   */\n  TJPF_CMYK,\n  /**\n   * Unknown pixel format\n   *\n   * Currently this is only used by #tj3LoadImage8(), #tj3LoadImage12(), and\n   * #tj3LoadImage16().\n   */\n  TJPF_UNKNOWN = -1\n};\n\n/**\n * Red offset (in samples) for a given pixel format\n *\n * This specifies the number of samples that the red component is offset from\n * the start of the pixel.  For instance, if an 8-bit-per-component pixel of\n * format TJPF_BGRX is stored in `unsigned char pixel[]`, then the red\n * component is `pixel[tjRedOffset[TJPF_BGRX]]`.  The offset is -1 if the pixel\n * format does not have a red component.\n */\nstatic const int tjRedOffset[TJ_NUMPF] = {\n  0, 2, 0, 2, 3, 1, -1, 0, 2, 3, 1, -1\n};\n/**\n * Green offset (in samples) for a given pixel format\n *\n * This specifies the number of samples that the green component is offset from\n * the start of the pixel.  For instance, if an 8-bit-per-component pixel of\n * format TJPF_BGRX is stored in `unsigned char pixel[]`, then the green\n * component is `pixel[tjGreenOffset[TJPF_BGRX]]`.  The offset is -1 if the\n * pixel format does not have a green component.\n */\nstatic const int tjGreenOffset[TJ_NUMPF] = {\n  1, 1, 1, 1, 2, 2, -1, 1, 1, 2, 2, -1\n};\n/**\n * Blue offset (in samples) for a given pixel format\n *\n * This specifies the number of samples that the blue component is offset from\n * the start of the pixel.  For instance, if an 8-bit-per-component pixel of\n * format TJPF_BGRX is stored in `unsigned char pixel[]`, then the blue\n * component is `pixel[tjBlueOffset[TJPF_BGRX]]`.  The offset is -1 if the\n * pixel format does not have a blue component.\n */\nstatic const int tjBlueOffset[TJ_NUMPF] = {\n  2, 0, 2, 0, 1, 3, -1, 2, 0, 1, 3, -1\n};\n/**\n * Alpha offset (in samples) for a given pixel format\n *\n * This specifies the number of samples that the alpha component is offset from\n * the start of the pixel.  For instance, if an 8-bit-per-component pixel of\n * format TJPF_BGRA is stored in `unsigned char pixel[]`, then the alpha\n * component is `pixel[tjAlphaOffset[TJPF_BGRA]]`.  The offset is -1 if the\n * pixel format does not have an alpha component.\n */\nstatic const int tjAlphaOffset[TJ_NUMPF] = {\n  -1, -1, -1, -1, -1, -1, -1, 3, 3, 0, 0, -1\n};\n/**\n * Pixel size (in samples) for a given pixel format\n */\nstatic const int tjPixelSize[TJ_NUMPF] = {\n  3, 3, 4, 4, 4, 4, 1, 4, 4, 4, 4, 4\n};\n\n\n/**\n * The number of JPEG colorspaces\n */\n#define TJ_NUMCS  5\n\n/**\n * JPEG colorspaces\n */\nenum TJCS {\n  /**\n   * RGB colorspace\n   *\n   * When generating the JPEG image, the R, G, and B components in the source\n   * image are reordered into image planes, but no colorspace conversion or\n   * subsampling is performed.  RGB JPEG images can be generated from and\n   * decompressed to packed-pixel images with any of the extended RGB or\n   * grayscale pixel formats, but they cannot be generated from or\n   * decompressed to planar YUV images.\n   */\n  TJCS_RGB,\n  /**\n   * YCbCr colorspace\n   *\n   * YCbCr is not an absolute colorspace but rather a mathematical\n   * transformation of RGB designed solely for storage and transmission.  YCbCr\n   * images must be converted to RGB before they can be displayed.  In the\n   * YCbCr colorspace, the Y (luminance) component represents the black & white\n   * portion of the original image, and the Cb and Cr (chrominance) components\n   * represent the color portion of the original image.  Historically, the\n   * analog equivalent of this transformation allowed the same signal to be\n   * displayed to both black & white and color televisions, but JPEG images use\n   * YCbCr primarily because it allows the color data to be optionally\n   * subsampled in order to reduce network and disk usage.  YCbCr is the most\n   * common JPEG colorspace, and YCbCr JPEG images can be generated from and\n   * decompressed to packed-pixel images with any of the extended RGB or\n   * grayscale pixel formats.  YCbCr JPEG images can also be generated from\n   * and decompressed to planar YUV images.\n   */\n  TJCS_YCbCr,\n  /**\n   * Grayscale colorspace\n   *\n   * The JPEG image retains only the luminance data (Y component), and any\n   * color data from the source image is discarded.  Grayscale JPEG images can\n   * be generated from and decompressed to packed-pixel images with any of the\n   * extended RGB or grayscale pixel formats, or they can be generated from\n   * and decompressed to planar YUV images.\n   */\n  TJCS_GRAY,\n  /**\n   * CMYK colorspace\n   *\n   * When generating the JPEG image, the C, M, Y, and K components in the\n   * source image are reordered into image planes, but no colorspace conversion\n   * or subsampling is performed.  CMYK JPEG images can only be generated from\n   * and decompressed to packed-pixel images with the CMYK pixel format.\n   */\n  TJCS_CMYK,\n  /**\n   * YCCK colorspace\n   *\n   * YCCK (AKA \"YCbCrK\") is not an absolute colorspace but rather a\n   * mathematical transformation of CMYK designed solely for storage and\n   * transmission.  It is to CMYK as YCbCr is to RGB.  CMYK pixels can be\n   * reversibly transformed into YCCK, and as with YCbCr, the chrominance\n   * components in the YCCK pixels can be subsampled without incurring major\n   * perceptual loss.  YCCK JPEG images can only be generated from and\n   * decompressed to packed-pixel images with the CMYK pixel format.\n   */\n  TJCS_YCCK\n};\n\n\n/**\n * Parameters\n */\nenum TJPARAM {\n  /**\n   * Error handling behavior\n   *\n   * **Value**\n   * - `0` *[default]* Allow the current compression/decompression/transform\n   * operation to complete unless a fatal error is encountered.\n   * - `1` Immediately discontinue the current\n   * compression/decompression/transform operation if a warning (non-fatal\n   * error) occurs.\n   */\n  TJPARAM_STOPONWARNING,\n  /**\n   * Row order in packed-pixel source/destination images\n   *\n   * **Value**\n   * - `0` *[default]* top-down (X11) order\n   * - `1` bottom-up (Windows, OpenGL) order\n   */\n  TJPARAM_BOTTOMUP,\n  /**\n   * JPEG destination buffer (re)allocation [compression, lossless\n   * transformation]\n   *\n   * **Value**\n   * - `0` *[default]* Attempt to allocate or reallocate the JPEG destination\n   * buffer as needed.\n   * - `1` Generate an error if the JPEG destination buffer is invalid or too\n   * small.\n   */\n  TJPARAM_NOREALLOC,\n  /**\n   * Perceptual quality of lossy JPEG images [compression only]\n   *\n   * **Value**\n   * - `1`-`100` (`1` = worst quality but best compression, `100` = best\n   * quality but worst compression) *[no default; must be explicitly\n   * specified]*\n   */\n  TJPARAM_QUALITY,\n  /**\n   * Chrominance subsampling level\n   *\n   * The JPEG or YUV image uses (decompression, decoding) or will use (lossy\n   * compression, encoding) the specified level of chrominance subsampling.\n   *\n   * **Value**\n   * - One of the @ref TJSAMP \"chrominance subsampling options\" *[no default;\n   * must be explicitly specified for lossy compression, encoding, and\n   * decoding]*\n   */\n  TJPARAM_SUBSAMP,\n  /**\n   * JPEG width (in pixels) [decompression only, read-only]\n   */\n  TJPARAM_JPEGWIDTH,\n  /**\n   * JPEG height (in pixels) [decompression only, read-only]\n   */\n  TJPARAM_JPEGHEIGHT,\n  /**\n   * Data precision (bits per sample)\n   *\n   * The JPEG image uses (decompression) or will use (lossless compression) the\n   * specified number of bits per sample.  This parameter also specifies the\n   * target data precision when loading a PBMPLUS file with #tj3LoadImage8(),\n   * #tj3LoadImage12(), or #tj3LoadImage16() and the source data precision when\n   * saving a PBMPLUS file with #tj3SaveImage8(), #tj3SaveImage12(), or\n   * #tj3SaveImage16().\n   *\n   * The data precision is the number of bits in the maximum sample value,\n   * which may not be the same as the width of the data type used to store the\n   * sample.\n   *\n   * **Value**\n   * - `8` or `12` for lossy JPEG images; `2` to `16` for lossless JPEG and\n   * PBMPLUS images\n   *\n   * 12-bit JPEG data precision implies #TJPARAM_OPTIMIZE unless\n   * #TJPARAM_ARITHMETIC is set.\n   */\n  TJPARAM_PRECISION,\n  /**\n   * JPEG colorspace\n   *\n   * The JPEG image uses (decompression) or will use (lossy compression) the\n   * specified colorspace.\n   *\n   * **Value**\n   * - One of the @ref TJCS \"JPEG colorspaces\" *[default for lossy compression:\n   * automatically selected based on the subsampling level and pixel format]*\n   */\n  TJPARAM_COLORSPACE,\n  /**\n   * Chrominance upsampling algorithm [lossy decompression only]\n   *\n   * **Value**\n   * - `0` *[default]* Use smooth upsampling when decompressing a JPEG image\n   * that was generated using chrominance subsampling.  This creates a smooth\n   * transition between neighboring chrominance components in order to reduce\n   * upsampling artifacts in the decompressed image.\n   * - `1` Use the fastest chrominance upsampling algorithm available, which\n   * may combine upsampling with color conversion.\n   */\n  TJPARAM_FASTUPSAMPLE,\n  /**\n   * DCT/IDCT algorithm [lossy compression and decompression]\n   *\n   * **Value**\n   * - `0` *[default]* Use the most accurate DCT/IDCT algorithm available.\n   * - `1` Use the fastest DCT/IDCT algorithm available.\n   *\n   * This parameter is provided mainly for backward compatibility with libjpeg,\n   * which historically implemented several different DCT/IDCT algorithms\n   * because of performance limitations with 1990s CPUs.  In the libjpeg-turbo\n   * implementation of the TurboJPEG API:\n   * - The \"fast\" and \"accurate\" DCT/IDCT algorithms perform similarly on\n   * modern x86/x86-64 CPUs that support AVX2 instructions.\n   * - The \"fast\" algorithm is generally only about 5-15% faster than the\n   * \"accurate\" algorithm on other types of CPUs.\n   * - The difference in accuracy between the \"fast\" and \"accurate\" algorithms\n   * is the most pronounced at JPEG quality levels above 90 and tends to be\n   * more pronounced with decompression than with compression.\n   * - For JPEG quality levels above 97, the \"fast\" algorithm degrades and is\n   * not fully accelerated, so it is slower than the \"accurate\" algorithm.\n   */\n  TJPARAM_FASTDCT,\n  /**\n   * Huffman table optimization [lossy compression, lossless transformation]\n   *\n   * **Value**\n   * - `0` *[default]* The JPEG image will use the default Huffman tables.\n   * - `1` Optimal Huffman tables will be computed for the JPEG image.  For\n   * lossless transformation, this can also be specified using\n   * #TJXOPT_OPTIMIZE.\n   *\n   * Huffman table optimization improves compression slightly (generally 5% or\n   * less), but it reduces compression performance considerably.\n   */\n  TJPARAM_OPTIMIZE,\n  /**\n   * Progressive JPEG\n   *\n   * In a progressive JPEG image, the DCT coefficients are split across\n   * multiple \"scans\" of increasing quality.  Thus, a low-quality scan\n   * containing the lowest-frequency DCT coefficients can be transmitted first\n   * and refined with subsequent higher-quality scans containing\n   * higher-frequency DCT coefficients.  When using Huffman entropy coding, the\n   * progressive JPEG format also provides an \"end-of-bands (EOB) run\" feature\n   * that allows large groups of zeroes, potentially spanning multiple MCUs,\n   * to be represented using only a few bytes.\n   *\n   * **Value**\n   * - `0` *[default for compression, lossless transformation]* The lossy JPEG\n   * image is (decompression) or will be (compression, lossless transformation)\n   * single-scan.\n   * - `1` The lossy JPEG image is (decompression) or will be (compression,\n   * lossless transformation) progressive.  For lossless transformation, this\n   * can also be specified using #TJXOPT_PROGRESSIVE.\n   *\n   * Progressive JPEG images generally have better compression ratios than\n   * single-scan JPEG images (much better if the image has large areas of solid\n   * color), but progressive JPEG compression and decompression is considerably\n   * slower than single-scan JPEG compression and decompression.  Can be\n   * combined with #TJPARAM_ARITHMETIC.  Implies #TJPARAM_OPTIMIZE unless\n   * #TJPARAM_ARITHMETIC is also set.\n   */\n  TJPARAM_PROGRESSIVE,\n  /**\n   * Progressive JPEG scan limit for lossy JPEG images [decompression, lossless\n   * transformation]\n   *\n   * Setting this parameter causes the decompression and transform functions to\n   * return an error if the number of scans in a progressive JPEG image exceeds\n   * the specified limit.  The primary purpose of this is to allow\n   * security-critical applications to guard against an exploit of the\n   * progressive JPEG format described in\n   * <a href=\"https://libjpeg-turbo.org/pmwiki/uploads/About/TwoIssueswiththeJPEGStandard.pdf\" target=\"_blank\">this report</a>.\n   *\n   * **Value**\n   * - maximum number of progressive JPEG scans that the decompression and\n   * transform functions will process *[default: `0` (no limit)]*\n   *\n   * @see #TJPARAM_PROGRESSIVE\n   */\n  TJPARAM_SCANLIMIT,\n  /**\n   * Arithmetic entropy coding\n   *\n   * **Value**\n   * - `0` *[default for compression, lossless transformation]* The lossy JPEG\n   * image uses (decompression) or will use (compression, lossless\n   * transformation) Huffman entropy coding.\n   * - `1` The lossy JPEG image uses (decompression) or will use (compression,\n   * lossless transformation) arithmetic entropy coding.  For lossless\n   * transformation, this can also be specified using #TJXOPT_ARITHMETIC.\n   *\n   * Arithmetic entropy coding generally improves compression relative to\n   * Huffman entropy coding, but it reduces compression and decompression\n   * performance considerably.  Can be combined with #TJPARAM_PROGRESSIVE.\n   */\n  TJPARAM_ARITHMETIC,\n  /**\n   * Lossless JPEG\n   *\n   * **Value**\n   * - `0` *[default for compression]* The JPEG image is (decompression) or\n   * will be (compression) lossy/DCT-based.\n   * - `1` The JPEG image is (decompression) or will be (compression)\n   * lossless/predictive.\n   *\n   * In most cases, lossless JPEG compression and decompression is considerably\n   * slower than lossy JPEG compression and decompression, and lossless JPEG\n   * images are much larger than lossy JPEG images.  Thus, lossless JPEG images\n   * are typically used only for applications that require mathematically\n   * lossless compression.  Also note that the following features are not\n   * available with lossless JPEG images:\n   * - Colorspace conversion (lossless JPEG images always use #TJCS_RGB,\n   * #TJCS_GRAY, or #TJCS_CMYK, depending on the pixel format of the source\n   * image)\n   * - Chrominance subsampling (lossless JPEG images always use #TJSAMP_444)\n   * - JPEG quality selection\n   * - DCT/IDCT algorithm selection\n   * - Progressive JPEG\n   * - Arithmetic entropy coding\n   * - Compression from/decompression to planar YUV images (this parameter is\n   * ignored by #tj3CompressFromYUV8() and #tj3CompressFromYUVPlanes8())\n   * - Decompression scaling\n   * - Lossless transformation\n   *\n   * @see #TJPARAM_LOSSLESSPSV, #TJPARAM_LOSSLESSPT\n   */\n  TJPARAM_LOSSLESS,\n  /**\n   * Lossless JPEG predictor selection value (PSV)\n   *\n   * **Value**\n   * - `1`-`7` *[default for compression: `1`]*\n   *\n   * Lossless JPEG compression shares no algorithms with lossy JPEG\n   * compression.  Instead, it uses differential pulse-code modulation (DPCM),\n   * an algorithm whereby each sample is encoded as the difference between the\n   * sample's value and a \"predictor\", which is based on the values of\n   * neighboring samples.  If Ra is the sample immediately to the left of the\n   * current sample, Rb is the sample immediately above the current sample, and\n   * Rc is the sample diagonally to the left and above the current sample, then\n   * the relationship between the predictor selection value and the predictor\n   * is as follows:\n   *\n   * PSV | Predictor\n   * ----|----------\n   * 1   | Ra\n   * 2   | Rb\n   * 3   | Rc\n   * 4   | Ra + Rb – Rc\n   * 5   | Ra + (Rb – Rc) / 2\n   * 6   | Rb + (Ra – Rc) / 2\n   * 7   | (Ra + Rb) / 2\n   *\n   * Predictors 1-3 are 1-dimensional predictors, whereas Predictors 4-7 are\n   * 2-dimensional predictors.  The best predictor for a particular image\n   * depends on the image.\n   *\n   * @see #TJPARAM_LOSSLESS\n   */\n  TJPARAM_LOSSLESSPSV,\n  /**\n   * Lossless JPEG point transform (Pt)\n   *\n   * **Value**\n   * - `0` through ***precision*** *- 1*, where ***precision*** is the JPEG\n   * data precision in bits *[default for compression: `0`]*\n   *\n   * A point transform value of `0` is necessary in order to generate a fully\n   * lossless JPEG image.  (A non-zero point transform value right-shifts the\n   * input samples by the specified number of bits, which is effectively a form\n   * of lossy color quantization.)\n   *\n   * @see #TJPARAM_LOSSLESS, #TJPARAM_PRECISION\n   */\n  TJPARAM_LOSSLESSPT,\n  /**\n   * JPEG restart marker interval in MCUs [lossy compression,\n   * lossless transformation]\n   *\n   * The nature of entropy coding is such that a corrupt JPEG image cannot\n   * be decompressed beyond the point of corruption unless it contains restart\n   * markers.  A restart marker stops and restarts the entropy coding algorithm\n   * so that, if a JPEG image is corrupted, decompression can resume at the\n   * next marker.  Thus, adding more restart markers improves the fault\n   * tolerance of the JPEG image, but adding too many restart markers can\n   * adversely affect the compression ratio and performance.\n   *\n   * In typical JPEG images, an MCU (Minimum Coded Unit) is the minimum set of\n   * interleaved \"data units\" (8x8 DCT blocks if the image is lossy or samples\n   * if the image is lossless) necessary to represent at least one data unit\n   * per component.  (For example, an MCU in an interleaved lossy JPEG image\n   * that uses 4:2:2 subsampling consists of two luminance blocks followed by\n   * one block for each chrominance component.)  In single-component or\n   * non-interleaved JPEG images, an MCU is the same as a data unit.\n   *\n   * **Value**\n   * - the number of MCUs between each restart marker *[default: `0` (no\n   * restart markers)]*\n   *\n   * Setting this parameter to a non-zero value sets #TJPARAM_RESTARTROWS to 0.\n   */\n  TJPARAM_RESTARTBLOCKS,\n  /**\n   * JPEG restart marker interval in MCU rows [compression,\n   * lossless transformation]\n   *\n   * See #TJPARAM_RESTARTBLOCKS for a description of restart markers and MCUs.\n   * An MCU row is a row of MCUs spanning the entire width of the image.\n   *\n   * **Value**\n   * - the number of MCU rows between each restart marker *[default: `0` (no\n   * restart markers)]*\n   *\n   * Setting this parameter to a non-zero value sets #TJPARAM_RESTARTBLOCKS to\n   * 0.\n   */\n  TJPARAM_RESTARTROWS,\n  /**\n   * JPEG horizontal pixel density\n   *\n   * **Value**\n   * - The JPEG image has (decompression) or will have (compression) the\n   * specified horizontal pixel density *[default for compression: `1`]*.\n   *\n   * This value is stored in or read from the JPEG header.  It does not affect\n   * the contents of the JPEG image.  Note that this parameter is set by\n   * #tj3LoadImage8() when loading a Windows BMP file that contains pixel\n   * density information, and the value of this parameter is stored to a\n   * Windows BMP file by #tj3SaveImage8() if the value of #TJPARAM_DENSITYUNITS\n   * is `2`.\n   *\n   * This parameter has no effect unless the JPEG colorspace (see\n   * #TJPARAM_COLORSPACE) is #TJCS_YCbCr or #TJCS_GRAY.\n   *\n   * @see TJPARAM_DENSITYUNITS\n   */\n  TJPARAM_XDENSITY,\n  /**\n   * JPEG vertical pixel density\n   *\n   * **Value**\n   * - The JPEG image has (decompression) or will have (compression) the\n   * specified vertical pixel density *[default for compression: `1`]*.\n   *\n   * This value is stored in or read from the JPEG header.  It does not affect\n   * the contents of the JPEG image.  Note that this parameter is set by\n   * #tj3LoadImage8() when loading a Windows BMP file that contains pixel\n   * density information, and the value of this parameter is stored to a\n   * Windows BMP file by #tj3SaveImage8() if the value of #TJPARAM_DENSITYUNITS\n   * is `2`.\n   *\n   * This parameter has no effect unless the JPEG colorspace (see\n   * #TJPARAM_COLORSPACE) is #TJCS_YCbCr or #TJCS_GRAY.\n   *\n   * @see TJPARAM_DENSITYUNITS\n   */\n  TJPARAM_YDENSITY,\n  /**\n   * JPEG pixel density units\n   *\n   * **Value**\n   * - `0` *[default for compression]* The pixel density of the JPEG image is\n   * expressed (decompression) or will be expressed (compression) in unknown\n   * units.\n   * - `1` The pixel density of the JPEG image is expressed (decompression) or\n   * will be expressed (compression) in units of pixels/inch.\n   * - `2` The pixel density of the JPEG image is expressed (decompression) or\n   * will be expressed (compression) in units of pixels/cm.\n   *\n   * This value is stored in or read from the JPEG header.  It does not affect\n   * the contents of the JPEG image.  Note that this parameter is set by\n   * #tj3LoadImage8() when loading a Windows BMP file that contains pixel\n   * density information, and the value of this parameter is stored to a\n   * Windows BMP file by #tj3SaveImage8() if the value is `2`.\n   *\n   * This parameter has no effect unless the JPEG colorspace (see\n   * #TJPARAM_COLORSPACE) is #TJCS_YCbCr or #TJCS_GRAY.\n   *\n   * @see TJPARAM_XDENSITY, TJPARAM_YDENSITY\n   */\n  TJPARAM_DENSITYUNITS,\n  /**\n   * Memory limit for intermediate buffers\n   *\n   * **Value**\n   * - the maximum amount of memory (in megabytes) that will be allocated for\n   * intermediate buffers, which are used with progressive JPEG compression and\n   * decompression, Huffman table optimization, lossless JPEG compression, and\n   * lossless transformation *[default: `0` (no limit)]*\n   */\n  TJPARAM_MAXMEMORY,\n  /**\n   * Image size limit [decompression, lossless transformation, packed-pixel\n   * image loading]\n   *\n   * Setting this parameter causes the decompression, transform, and image\n   * loading functions to return an error if the number of pixels in the source\n   * image exceeds the specified limit.  This allows security-critical\n   * applications to guard against excessive memory consumption.\n   *\n   * **Value**\n   * - maximum number of pixels that the decompression, transform, and image\n   * loading functions will process *[default: `0` (no limit)]*\n   */\n  TJPARAM_MAXPIXELS,\n  /**\n   * Marker copying behavior [decompression, lossless transformation]\n   *\n   * **Value [lossless transformation]**\n   * - `0` Do not copy any extra markers (including comments, JFIF thumbnails,\n   * Exif data, and ICC profile data) from the source image to the destination\n   * image.\n   * - `1` Do not copy any extra markers, except comment (COM) markers, from\n   * the source image to the destination image.\n   * - `2` *[default]* Copy all extra markers from the source image to the\n   * destination image.\n   * - `3` Copy all extra markers, except ICC profile data (APP2 markers), from\n   * the source image to the destination image.\n   * - `4` Do not copy any extra markers, except ICC profile data (APP2\n   * markers), from the source image to the destination image.\n   *\n   * #TJXOPT_COPYNONE overrides this parameter for a particular transform.\n   * This parameter overrides any ICC profile that was previously associated\n   * with the TurboJPEG instance using #tj3SetICCProfile().\n   *\n   * When decompressing, #tj3DecompressHeader() extracts the ICC profile from a\n   * JPEG image if this parameter is set to `2` or `4`.  #tj3GetICCProfile()\n   * can then be used to retrieve the profile.\n   */\n  TJPARAM_SAVEMARKERS\n};\n\n\n/**\n * The number of error codes\n */\n#define TJ_NUMERR  2\n\n/**\n * Error codes\n */\nenum TJERR {\n  /**\n   * The error was non-fatal and recoverable, but the destination image may\n   * still be corrupt.\n   */\n  TJERR_WARNING,\n  /**\n   * The error was fatal and non-recoverable.\n   */\n  TJERR_FATAL\n};\n\n\n/**\n * The number of transform operations\n */\n#define TJ_NUMXOP  8\n\n/**\n * Transform operations for #tj3Transform()\n */\nenum TJXOP {\n  /**\n   * Do not transform the position of the image pixels.\n   */\n  TJXOP_NONE,\n  /**\n   * Flip (mirror) image horizontally.  This transform is imperfect if there\n   * are any partial iMCUs on the right edge (see #TJXOPT_PERFECT.)\n   */\n  TJXOP_HFLIP,\n  /**\n   * Flip (mirror) image vertically.  This transform is imperfect if there are\n   * any partial iMCUs on the bottom edge (see #TJXOPT_PERFECT.)\n   */\n  TJXOP_VFLIP,\n  /**\n   * Transpose image (flip/mirror along upper left to lower right axis.)  This\n   * transform is always perfect.\n   */\n  TJXOP_TRANSPOSE,\n  /**\n   * Transverse transpose image (flip/mirror along upper right to lower left\n   * axis.)  This transform is imperfect if there are any partial iMCUs in the\n   * image (see #TJXOPT_PERFECT.)\n   */\n  TJXOP_TRANSVERSE,\n  /**\n   * Rotate image clockwise by 90 degrees.  This transform is imperfect if\n   * there are any partial iMCUs on the bottom edge (see #TJXOPT_PERFECT.)\n   */\n  TJXOP_ROT90,\n  /**\n   * Rotate image 180 degrees.  This transform is imperfect if there are any\n   * partial iMCUs in the image (see #TJXOPT_PERFECT.)\n   */\n  TJXOP_ROT180,\n  /**\n   * Rotate image counter-clockwise by 90 degrees.  This transform is imperfect\n   * if there are any partial iMCUs on the right edge (see #TJXOPT_PERFECT.)\n   */\n  TJXOP_ROT270\n};\n\n\n/**\n * This option causes #tj3Transform() to return an error if the transform is\n * not perfect.  Lossless transforms operate on iMCUs, the size of which\n * depends on the level of chrominance subsampling used (see #tjMCUWidth and\n * #tjMCUHeight.)  If the image's width or height is not evenly divisible by\n * the iMCU size, then there will be partial iMCUs on the right and/or bottom\n * edges.  It is not possible to move these partial iMCUs to the top or left of\n * the image, so any transform that would require that is \"imperfect.\"  If this\n * option is not specified, then any partial iMCUs that cannot be transformed\n * will be left in place, which will create odd-looking strips on the right or\n * bottom edge of the image.\n */\n#define TJXOPT_PERFECT  (1 << 0)\n/**\n * Discard any partial iMCUs that cannot be transformed.\n */\n#define TJXOPT_TRIM  (1 << 1)\n/**\n * Enable lossless cropping.  See #tj3Transform() for more information.\n */\n#define TJXOPT_CROP  (1 << 2)\n/**\n * Discard the color data in the source image, and generate a grayscale\n * destination image.\n */\n#define TJXOPT_GRAY  (1 << 3)\n/**\n * Do not generate a destination image.  (This can be used in conjunction with\n * a custom filter to capture the transformed DCT coefficients without\n * transcoding them.)\n */\n#define TJXOPT_NOOUTPUT  (1 << 4)\n/**\n * Generate a progressive destination image instead of a single-scan\n * destination image.  Progressive JPEG images generally have better\n * compression ratios than single-scan JPEG images (much better if the image\n * has large areas of solid color), but progressive JPEG decompression is\n * considerably slower than single-scan JPEG decompression.  Can be combined\n * with #TJXOPT_ARITHMETIC.  Implies #TJXOPT_OPTIMIZE unless #TJXOPT_ARITHMETIC\n * is also specified.\n */\n#define TJXOPT_PROGRESSIVE  (1 << 5)\n/**\n * Do not copy any extra markers (including Exif and ICC profile data) from the\n * source image to the destination image.\n */\n#define TJXOPT_COPYNONE  (1 << 6)\n/**\n * Enable arithmetic entropy coding in the destination image.  Arithmetic\n * entropy coding generally improves compression relative to Huffman entropy\n * coding (the default), but it reduces decompression performance considerably.\n * Can be combined with #TJXOPT_PROGRESSIVE.\n */\n#define TJXOPT_ARITHMETIC  (1 << 7)\n/**\n * Enable Huffman table optimization for the destination image.  Huffman table\n * optimization improves compression slightly (generally 5% or less.)\n */\n#define TJXOPT_OPTIMIZE  (1 << 8)\n\n\n/**\n * Scaling factor\n */\ntypedef struct {\n  /**\n   * Numerator\n   */\n  int num;\n  /**\n   * Denominator\n   */\n  int denom;\n} tjscalingfactor;\n\n/**\n * Cropping region\n */\ntypedef struct {\n  /**\n   * The left boundary of the cropping region.  For lossless transformation,\n   * this must be evenly divisible by the iMCU width (see #tjMCUWidth) of the\n   * destination image.  For decompression, this must be evenly divisible by\n   * the scaled iMCU width of the source image.\n   */\n  int x;\n  /**\n   * The upper boundary of the cropping region.  For lossless transformation,\n   * this must be evenly divisible by the iMCU height (see #tjMCUHeight) of the\n   * destination image.\n   */\n  int y;\n  /**\n   * The width of the cropping region.  Setting this to 0 is the equivalent of\n   * setting it to the width of the source JPEG image - x.\n   */\n  int w;\n  /**\n   * The height of the cropping region.  Setting this to 0 is the equivalent of\n   * setting it to the height of the source JPEG image - y.\n   */\n  int h;\n} tjregion;\n\n/**\n * A #tjregion structure that specifies no cropping\n */\nstatic const tjregion TJUNCROPPED = { 0, 0, 0, 0 };\n\n/**\n * Lossless transform\n */\ntypedef struct tjtransform {\n  /**\n   * Cropping region\n   */\n  tjregion r;\n  /**\n   * One of the @ref TJXOP \"transform operations\"\n   */\n  int op;\n  /**\n   * The bitwise OR of one of more of the @ref TJXOPT_ARITHMETIC\n   * \"transform options\"\n   */\n  int options;\n  /**\n   * Arbitrary data that can be accessed within the body of the callback\n   * function\n   */\n  void *data;\n  /**\n   * A callback function that can be used to modify the DCT coefficients after\n   * they are losslessly transformed but before they are transcoded to a new\n   * JPEG image.  This allows for custom filters or other transformations to be\n   * applied in the frequency domain.\n   *\n   * @param coeffs pointer to an array of transformed DCT coefficients.  (NOTE:\n   * This pointer is not guaranteed to be valid once the callback returns, so\n   * applications wishing to hand off the DCT coefficients to another function\n   * or library should make a copy of them within the body of the callback.)\n   *\n   * @param arrayRegion #tjregion structure containing the width and height of\n   * the array pointed to by `coeffs` as well as its offset relative to the\n   * component plane.  TurboJPEG implementations may choose to split each\n   * component plane into multiple DCT coefficient arrays and call the callback\n   * function once for each array.\n   *\n   * @param planeRegion #tjregion structure containing the width and height of\n   * the component plane to which `coeffs` belongs\n   *\n   * @param componentID ID number of the component plane to which `coeffs`\n   * belongs.  (Y, Cb, and Cr have, respectively, ID's of 0, 1, and 2 in\n   * typical JPEG images.)\n   *\n   * @param transformID ID number of the transformed image to which `coeffs`\n   * belongs.  This is the same as the index of the transform in the\n   * `transforms` array that was passed to #tj3Transform().\n   *\n   * @param transform a pointer to a #tjtransform structure that specifies the\n   * parameters and/or cropping region for this transform\n   *\n   * @return 0 if the callback was successful, or -1 if an error occurred.\n   */\n  int (*customFilter) (short *coeffs, tjregion arrayRegion,\n                       tjregion planeRegion, int componentID, int transformID,\n                       struct tjtransform *transform);\n} tjtransform;\n\n/**\n * TurboJPEG instance handle\n */\ntypedef void *tjhandle;\n\n\n/**\n * Compute the scaled value of `dimension` using the given scaling factor.\n * This macro performs the integer equivalent of `ceil(dimension *\n * scalingFactor)`.\n */\n#define TJSCALED(dimension, scalingFactor) \\\n  (((dimension) * scalingFactor.num + scalingFactor.denom - 1) / \\\n   scalingFactor.denom)\n\n/**\n * A #tjscalingfactor structure that specifies a scaling factor of 1/1 (no\n * scaling)\n */\nstatic const tjscalingfactor TJUNSCALED = { 1, 1 };\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\n/**\n * Create a new TurboJPEG instance.\n *\n * @param initType one of the @ref TJINIT \"initialization options\"\n *\n * @return a handle to the newly-created instance, or NULL if an error occurred\n * (see #tj3GetErrorStr().)\n */\nDLLEXPORT tjhandle tj3Init(int initType);\n\n\n/**\n * Destroy a TurboJPEG instance.\n *\n * @param handle handle to a TurboJPEG instance.  If the handle is NULL, then\n * this function has no effect.\n */\nDLLEXPORT void tj3Destroy(tjhandle handle);\n\n\n/**\n * Returns a descriptive error message explaining why the last command failed.\n *\n * @param handle handle to a TurboJPEG instance, or NULL if the error was\n * generated by a global function (but note that retrieving the error message\n * for a global function is thread-safe only on platforms that support\n * thread-local storage.)\n *\n * @return a descriptive error message explaining why the last command failed.\n */\nDLLEXPORT char *tj3GetErrorStr(tjhandle handle);\n\n\n/**\n * Returns a code indicating the severity of the last error.  See\n * @ref TJERR \"Error codes\".\n *\n * @param handle handle to a TurboJPEG instance\n *\n * @return a code indicating the severity of the last error.  See\n * @ref TJERR \"Error codes\".\n */\nDLLEXPORT int tj3GetErrorCode(tjhandle handle);\n\n\n/**\n * Set the value of a parameter.\n *\n * @param handle handle to a TurboJPEG instance\n *\n * @param param one of the @ref TJPARAM \"parameters\"\n *\n * @param value value of the parameter (refer to @ref TJPARAM\n * \"parameter documentation\")\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr().)\n */\nDLLEXPORT int tj3Set(tjhandle handle, int param, int value);\n\n\n/**\n * Get the value of a parameter.\n *\n * @param handle handle to a TurboJPEG instance\n *\n * @param param one of the @ref TJPARAM \"parameters\"\n *\n * @return the value of the specified parameter, or -1 if the value is unknown.\n */\nDLLEXPORT int tj3Get(tjhandle handle, int param);\n\n\n/**\n * Allocate a byte buffer for use with TurboJPEG.  You should always use this\n * function to allocate the JPEG destination buffer(s) for the compression and\n * transform functions unless you are disabling automatic buffer (re)allocation\n * (by setting #TJPARAM_NOREALLOC.)\n *\n * @param bytes the number of bytes to allocate\n *\n * @return a pointer to a newly-allocated buffer with the specified number of\n * bytes.\n *\n * @see tj3Free()\n */\nDLLEXPORT void *tj3Alloc(size_t bytes);\n\n\n/**\n * Free a byte buffer previously allocated by TurboJPEG.  You should always use\n * this function to free JPEG destination buffer(s) that were automatically\n * (re)allocated by the compression and transform functions or that were\n * manually allocated using #tj3Alloc().\n *\n * @param buffer address of the buffer to free.  If the address is NULL, then\n * this function has no effect.\n *\n * @see tj3Alloc()\n */\nDLLEXPORT void tj3Free(void *buffer);\n\n\n/**\n * The maximum size of the buffer (in bytes) required to hold a JPEG image with\n * the given parameters.  The number of bytes returned by this function is\n * larger than the size of the uncompressed source image.  The reason for this\n * is that the JPEG format uses 16-bit coefficients, so it is possible for a\n * very high-quality source image with very high-frequency content to expand\n * rather than compress when converted to the JPEG format.  Such images\n * represent very rare corner cases, but since there is no way to predict the\n * size of a JPEG image prior to compression, the corner cases have to be\n * handled.\n *\n * @param width width (in pixels) of the image\n *\n * @param height height (in pixels) of the image\n *\n * @param jpegSubsamp the level of chrominance subsampling to be used when\n * generating the JPEG image (see @ref TJSAMP\n * \"Chrominance subsampling options\".)  #TJSAMP_UNKNOWN is treated like\n * #TJSAMP_444, since a buffer large enough to hold a JPEG image with no\n * subsampling should also be large enough to hold a JPEG image with an\n * arbitrary level of subsampling.  Note that lossless JPEG images always\n * use #TJSAMP_444.\n *\n * @return the maximum size of the buffer (in bytes) required to hold the\n * image, or 0 if the arguments are out of bounds.\n */\nDLLEXPORT size_t tj3JPEGBufSize(int width, int height, int jpegSubsamp);\n\n\n/**\n * The size of the buffer (in bytes) required to hold a unified planar YUV\n * image with the given parameters.\n *\n * @param width width (in pixels) of the image\n *\n * @param align row alignment (in bytes) of the image (must be a power of 2.)\n * Setting this parameter to n specifies that each row in each plane of the\n * image will be padded to the nearest multiple of n bytes (1 = unpadded.)\n *\n * @param height height (in pixels) of the image\n *\n * @param subsamp level of chrominance subsampling in the image (see\n * @ref TJSAMP \"Chrominance subsampling options\".)\n *\n * @return the size of the buffer (in bytes) required to hold the image, or 0\n * if the arguments are out of bounds.\n */\nDLLEXPORT size_t tj3YUVBufSize(int width, int align, int height, int subsamp);\n\n\n/**\n * The size of the buffer (in bytes) required to hold a YUV image plane with\n * the given parameters.\n *\n * @param componentID ID number of the image plane (0 = Y, 1 = U/Cb, 2 = V/Cr)\n *\n * @param width width (in pixels) of the YUV image.  NOTE: This is the width of\n * the whole image, not the plane width.\n *\n * @param stride bytes per row in the image plane.  Setting this to 0 is the\n * equivalent of setting it to the plane width.\n *\n * @param height height (in pixels) of the YUV image.  NOTE: This is the height\n * of the whole image, not the plane height.\n *\n * @param subsamp level of chrominance subsampling in the image (see\n * @ref TJSAMP \"Chrominance subsampling options\".)\n *\n * @return the size of the buffer (in bytes) required to hold the YUV image\n * plane, or 0 if the arguments are out of bounds.\n */\nDLLEXPORT size_t tj3YUVPlaneSize(int componentID, int width, int stride,\n                                 int height, int subsamp);\n\n\n/**\n * The plane width of a YUV image plane with the given parameters.  Refer to\n * @ref YUVnotes \"YUV Image Format Notes\" for a description of plane width.\n *\n * @param componentID ID number of the image plane (0 = Y, 1 = U/Cb, 2 = V/Cr)\n *\n * @param width width (in pixels) of the YUV image\n *\n * @param subsamp level of chrominance subsampling in the image (see\n * @ref TJSAMP \"Chrominance subsampling options\".)\n *\n * @return the plane width of a YUV image plane with the given parameters, or 0\n * if the arguments are out of bounds.\n */\nDLLEXPORT int tj3YUVPlaneWidth(int componentID, int width, int subsamp);\n\n\n/**\n * The plane height of a YUV image plane with the given parameters.  Refer to\n * @ref YUVnotes \"YUV Image Format Notes\" for a description of plane height.\n *\n * @param componentID ID number of the image plane (0 = Y, 1 = U/Cb, 2 = V/Cr)\n *\n * @param height height (in pixels) of the YUV image\n *\n * @param subsamp level of chrominance subsampling in the image (see\n * @ref TJSAMP \"Chrominance subsampling options\".)\n *\n * @return the plane height of a YUV image plane with the given parameters, or\n * 0 if the arguments are out of bounds.\n */\nDLLEXPORT int tj3YUVPlaneHeight(int componentID, int height, int subsamp);\n\n\n/**\n * Embed an ICC (International Color Consortium) color management profile in\n * JPEG images generated by subsequent compression and lossless transformation\n * operations.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * compression\n *\n * @param iccBuf pointer to a byte buffer containing an ICC profile.  A copy is\n * made of the ICC profile, so this buffer can be freed or reused as soon as\n * this function returns.  Setting this parameter to NULL or setting `iccSize`\n * to 0 removes any ICC profile that was previously associated with the\n * TurboJPEG instance.\n *\n * @param iccSize size of the ICC profile (in bytes.)  Setting this parameter\n * to 0 or setting `iccBuf` to NULL removes any ICC profile that was previously\n * associated with the TurboJPEG instance.\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr().)\n */\nDLLEXPORT int tj3SetICCProfile(tjhandle handle, unsigned char *iccBuf,\n                               size_t iccSize);\n\n\n/**\n * Compress a packed-pixel RGB, grayscale, or CMYK image with 2 to 8 bits of\n * data precision per sample into a JPEG image with the same data precision.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * compression\n *\n * @param srcBuf pointer to a buffer containing a packed-pixel RGB, grayscale,\n * or CMYK source image to be compressed.  This buffer should normally be\n * `pitch * height` samples in size.  However, you can also use this parameter\n * to compress from a specific region of a larger buffer.  The data precision\n * of the source image (from 2 to 8 bits per sample) can be specified using\n * #TJPARAM_PRECISION and defaults to 8 if #TJPARAM_PRECISION is unset or out\n * of range.\n *\n * @param width width (in pixels) of the source image\n *\n * @param pitch samples per row in the source image.  Normally this should be\n * <tt>width * #tjPixelSize[pixelFormat]</tt>, if the image is unpadded.\n * (Setting this parameter to 0 is the equivalent of setting it to\n * <tt>width * #tjPixelSize[pixelFormat]</tt>.)  However, you can also use this\n * parameter to specify the row alignment/padding of the source image, to skip\n * rows, or to compress from a specific region of a larger buffer.\n *\n * @param height height (in pixels) of the source image\n *\n * @param pixelFormat pixel format of the source image (see @ref TJPF\n * \"Pixel formats\".)\n *\n * @param jpegBuf address of a pointer to a byte buffer that will receive the\n * JPEG image.  TurboJPEG has the ability to reallocate the JPEG buffer to\n * accommodate the size of the JPEG image.  Thus, you can choose to:\n * -# pre-allocate the JPEG buffer with an arbitrary size using #tj3Alloc() and\n * let TurboJPEG grow the buffer as needed,\n * -# set `*jpegBuf` to NULL to tell TurboJPEG to allocate the buffer for you,\n * or\n * -# pre-allocate the buffer to a \"worst case\" size determined by calling\n * #tj3JPEGBufSize() and adding the return value to the size of the ICC profile\n * (if any) that was previously associated with the TurboJPEG instance (see\n * #tj3SetICCProfile().)  This should ensure that the buffer never has to be\n * re-allocated.  (Setting #TJPARAM_NOREALLOC guarantees that it won't be.)\n * .\n * Unless you have set #TJPARAM_NOREALLOC, you should always check `*jpegBuf`\n * upon return from this function, as it may have changed.\n *\n * @param jpegSize pointer to a size_t variable that holds the size of the JPEG\n * buffer.  If `*jpegBuf` points to a pre-allocated buffer, then `*jpegSize`\n * should be set to the size of the buffer.  Otherwise, `*jpegSize` is\n * ignored.  If `*jpegBuf` points to a JPEG buffer that is being reused from a\n * previous call to one of the JPEG compression functions, then `*jpegSize` is\n * also ignored.  Upon return, `*jpegSize` will contain the size of the JPEG\n * image (in bytes.)\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr()\n * and #tj3GetErrorCode().)\n */\nDLLEXPORT int tj3Compress8(tjhandle handle, const unsigned char *srcBuf,\n                           int width, int pitch, int height, int pixelFormat,\n                           unsigned char **jpegBuf, size_t *jpegSize);\n\n/**\n * Compress a packed-pixel RGB, grayscale, or CMYK image with 9 to 12 bits of\n * data precision per sample into a JPEG image with the same data precision.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * compression\n *\n * @param srcBuf pointer to a buffer containing a packed-pixel RGB, grayscale,\n * or CMYK source image to be compressed.  This buffer should normally be\n * `pitch * height` samples in size.  However, you can also use this parameter\n * to compress from a specific region of a larger buffer.  The data precision\n * of the source image (from 9 to 12 bits per sample) can be specified using\n * #TJPARAM_PRECISION and defaults to 12 if #TJPARAM_PRECISION is unset or out\n * of range.\n *\n * @param width width (in pixels) of the source image\n *\n * @param pitch samples per row in the source image.  Normally this should be\n * <tt>width * #tjPixelSize[pixelFormat]</tt>, if the image is unpadded.\n * (Setting this parameter to 0 is the equivalent of setting it to\n * <tt>width * #tjPixelSize[pixelFormat]</tt>.)  However, you can also use this\n * parameter to specify the row alignment/padding of the source image, to skip\n * rows, or to compress from a specific region of a larger buffer.\n *\n * @param height height (in pixels) of the source image\n *\n * @param pixelFormat pixel format of the source image (see @ref TJPF\n * \"Pixel formats\".)\n *\n * @param jpegBuf address of a pointer to a byte buffer that will receive the\n * JPEG image.  TurboJPEG has the ability to reallocate the JPEG buffer to\n * accommodate the size of the JPEG image.  Thus, you can choose to:\n * -# pre-allocate the JPEG buffer with an arbitrary size using #tj3Alloc() and\n * let TurboJPEG grow the buffer as needed,\n * -# set `*jpegBuf` to NULL to tell TurboJPEG to allocate the buffer for you,\n * or\n * -# pre-allocate the buffer to a \"worst case\" size determined by calling\n * #tj3JPEGBufSize() and adding the return value to the size of the ICC profile\n * (if any) that was previously associated with the TurboJPEG instance (see\n * #tj3SetICCProfile().)  This should ensure that the buffer never has to be\n * re-allocated.  (Setting #TJPARAM_NOREALLOC guarantees that it won't be.)\n * .\n * Unless you have set #TJPARAM_NOREALLOC, you should always check `*jpegBuf`\n * upon return from this function, as it may have changed.\n *\n * @param jpegSize pointer to a size_t variable that holds the size of the JPEG\n * buffer.  If `*jpegBuf` points to a pre-allocated buffer, then `*jpegSize`\n * should be set to the size of the buffer.  Otherwise, `*jpegSize` is\n * ignored.  If `*jpegBuf` points to a JPEG buffer that is being reused from a\n * previous call to one of the JPEG compression functions, then `*jpegSize` is\n * also ignored.  Upon return, `*jpegSize` will contain the size of the JPEG\n * image (in bytes.)\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr()\n * and #tj3GetErrorCode().)\n */\nDLLEXPORT int tj3Compress12(tjhandle handle, const short *srcBuf, int width,\n                            int pitch, int height, int pixelFormat,\n                            unsigned char **jpegBuf, size_t *jpegSize);\n\n/**\n * Compress a packed-pixel RGB, grayscale, or CMYK image with 13 to 16 bits of\n * data precision per sample into a lossless JPEG image with the same data\n * precision.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * compression\n *\n * @param srcBuf pointer to a buffer containing a packed-pixel RGB, grayscale,\n * or CMYK source image to be compressed.  This buffer should normally be\n * `pitch * height` samples in size.  However, you can also use this parameter\n * to compress from a specific region of a larger buffer.  The data precision\n * of the source image (from 13 to 16 bits per sample) can be specified using\n * #TJPARAM_PRECISION and defaults to 16 if #TJPARAM_PRECISION is unset or out\n * of range.\n *\n * @param width width (in pixels) of the source image\n *\n * @param pitch samples per row in the source image.  Normally this should be\n * <tt>width * #tjPixelSize[pixelFormat]</tt>, if the image is unpadded.\n * (Setting this parameter to 0 is the equivalent of setting it to\n * <tt>width * #tjPixelSize[pixelFormat]</tt>.)  However, you can also use this\n * parameter to specify the row alignment/padding of the source image, to skip\n * rows, or to compress from a specific region of a larger buffer.\n *\n * @param height height (in pixels) of the source image\n *\n * @param pixelFormat pixel format of the source image (see @ref TJPF\n * \"Pixel formats\".)\n *\n * @param jpegBuf address of a pointer to a byte buffer that will receive the\n * JPEG image.  TurboJPEG has the ability to reallocate the JPEG buffer to\n * accommodate the size of the JPEG image.  Thus, you can choose to:\n * -# pre-allocate the JPEG buffer with an arbitrary size using #tj3Alloc() and\n * let TurboJPEG grow the buffer as needed,\n * -# set `*jpegBuf` to NULL to tell TurboJPEG to allocate the buffer for you,\n * or\n * -# pre-allocate the buffer to a \"worst case\" size determined by calling\n * #tj3JPEGBufSize() and adding the return value to the size of the ICC profile\n * (if any) that was previously associated with the TurboJPEG instance (see\n * #tj3SetICCProfile().)  This should ensure that the buffer never has to be\n * re-allocated.  (Setting #TJPARAM_NOREALLOC guarantees that it won't be.)\n * .\n * Unless you have set #TJPARAM_NOREALLOC, you should always check `*jpegBuf`\n * upon return from this function, as it may have changed.\n *\n * @param jpegSize pointer to a size_t variable that holds the size of the JPEG\n * buffer.  If `*jpegBuf` points to a pre-allocated buffer, then `*jpegSize`\n * should be set to the size of the buffer.  Otherwise, `*jpegSize` is\n * ignored.  If `*jpegBuf` points to a JPEG buffer that is being reused from a\n * previous call to one of the JPEG compression functions, then `*jpegSize` is\n * also ignored.  Upon return, `*jpegSize` will contain the size of the JPEG\n * image (in bytes.)\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr()\n * and #tj3GetErrorCode().)\n */\nDLLEXPORT int tj3Compress16(tjhandle handle, const unsigned short *srcBuf,\n                            int width, int pitch, int height, int pixelFormat,\n                            unsigned char **jpegBuf, size_t *jpegSize);\n\n\n/**\n * Compress a set of 8-bit-per-sample Y, U (Cb), and V (Cr) image planes into\n * an 8-bit-per-sample lossy @ref TJCS_YCbCr \"YCbCr\" or\n * @ref TJCS_GRAY \"grayscale\" JPEG image.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * compression\n *\n * @param srcPlanes an array of pointers to Y, U (Cb), and V (Cr) image planes\n * (or just a Y plane, if compressing a grayscale image) that contain a YUV\n * source image to be compressed.  These planes can be contiguous or\n * non-contiguous in memory.  The size of each plane should match the value\n * returned by #tj3YUVPlaneSize() for the given image width, height, strides,\n * and level of chrominance subsampling (see #TJPARAM_SUBSAMP.)  Refer to\n * @ref YUVnotes \"YUV Image Format Notes\" for more details.\n *\n * @param width width (in pixels) of the source image.  If the width is not an\n * even multiple of the iMCU width (see #tjMCUWidth), then an intermediate\n * buffer copy will be performed.\n *\n * @param strides an array of integers, each specifying the number of bytes per\n * row in the corresponding plane of the YUV source image.  Setting the stride\n * for any plane to 0 is the same as setting it to the plane width (see\n * @ref YUVnotes \"YUV Image Format Notes\".)  If `strides` is NULL, then the\n * strides for all planes will be set to their respective plane widths.  You\n * can adjust the strides in order to specify an arbitrary amount of row\n * padding in each plane or to create a JPEG image from a subregion of a larger\n * planar YUV image.\n *\n * @param height height (in pixels) of the source image.  If the height is not\n * an even multiple of the iMCU height (see #tjMCUHeight), then an intermediate\n * buffer copy will be performed.\n *\n * @param jpegBuf address of a pointer to a byte buffer that will receive the\n * JPEG image.  TurboJPEG has the ability to reallocate the JPEG buffer to\n * accommodate the size of the JPEG image.  Thus, you can choose to:\n * -# pre-allocate the JPEG buffer with an arbitrary size using #tj3Alloc() and\n * let TurboJPEG grow the buffer as needed,\n * -# set `*jpegBuf` to NULL to tell TurboJPEG to allocate the buffer for you,\n * or\n * -# pre-allocate the buffer to a \"worst case\" size determined by calling\n * #tj3JPEGBufSize() and adding the return value to the size of the ICC profile\n * (if any) that was previously associated with the TurboJPEG instance (see\n * #tj3SetICCProfile().)  This should ensure that the buffer never has to be\n * re-allocated.  (Setting #TJPARAM_NOREALLOC guarantees that it won't be.)\n * .\n * Unless you have set #TJPARAM_NOREALLOC, you should always check `*jpegBuf`\n * upon return from this function, as it may have changed.\n *\n * @param jpegSize pointer to a size_t variable that holds the size of the JPEG\n * buffer.  If `*jpegBuf` points to a pre-allocated buffer, then `*jpegSize`\n * should be set to the size of the buffer.  Otherwise, `*jpegSize` is\n * ignored.  If `*jpegBuf` points to a JPEG buffer that is being reused from a\n * previous call to one of the JPEG compression functions, then `*jpegSize` is\n * also ignored.  Upon return, `*jpegSize` will contain the size of the JPEG\n * image (in bytes.)\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr()\n * and #tj3GetErrorCode().)\n */\nDLLEXPORT int tj3CompressFromYUVPlanes8(tjhandle handle,\n                                        const unsigned char * const *srcPlanes,\n                                        int width, const int *strides,\n                                        int height, unsigned char **jpegBuf,\n                                        size_t *jpegSize);\n\n\n/**\n * Compress an 8-bit-per-sample unified planar YUV image into an\n * 8-bit-per-sample lossy @ref TJCS_YCbCr \"YCbCr\" or @ref TJCS_GRAY \"grayscale\"\n * JPEG image.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * compression\n *\n * @param srcBuf pointer to a buffer containing a unified planar YUV source\n * image to be compressed.  The size of this buffer should match the value\n * returned by #tj3YUVBufSize() for the given image width, height, row\n * alignment, and level of chrominance subsampling (see #TJPARAM_SUBSAMP.)  The\n * Y, U (Cb), and V (Cr) image planes should be stored sequentially in the\n * buffer.  (Refer to @ref YUVnotes \"YUV Image Format Notes\".)\n *\n * @param width width (in pixels) of the source image.  If the width is not an\n * even multiple of the iMCU width (see #tjMCUWidth), then an intermediate\n * buffer copy will be performed.\n *\n * @param align row alignment (in bytes) of the source image (must be a power\n * of 2.)  Setting this parameter to n indicates that each row in each plane of\n * the source image is padded to the nearest multiple of n bytes\n * (1 = unpadded.)\n *\n * @param height height (in pixels) of the source image.  If the height is not\n * an even multiple of the iMCU height (see #tjMCUHeight), then an intermediate\n * buffer copy will be performed.\n *\n * @param jpegBuf address of a pointer to a byte buffer that will receive the\n * JPEG image.  TurboJPEG has the ability to reallocate the JPEG buffer to\n * accommodate the size of the JPEG image.  Thus, you can choose to:\n * -# pre-allocate the JPEG buffer with an arbitrary size using #tj3Alloc() and\n * let TurboJPEG grow the buffer as needed,\n * -# set `*jpegBuf` to NULL to tell TurboJPEG to allocate the buffer for you,\n * or\n * -# pre-allocate the buffer to a \"worst case\" size determined by calling\n * #tj3JPEGBufSize() and adding the return value to the size of the ICC profile\n * (if any) that was previously associated with the TurboJPEG instance (see\n * #tj3SetICCProfile().)  This should ensure that the buffer never has to be\n * re-allocated.  (Setting #TJPARAM_NOREALLOC guarantees that it won't be.)\n * .\n * Unless you have set #TJPARAM_NOREALLOC, you should always check `*jpegBuf`\n * upon return from this function, as it may have changed.\n *\n * @param jpegSize pointer to a size_t variable that holds the size of the JPEG\n * buffer.  If `*jpegBuf` points to a pre-allocated buffer, then `*jpegSize`\n * should be set to the size of the buffer.  Otherwise, `*jpegSize` is\n * ignored.  If `*jpegBuf` points to a JPEG buffer that is being reused from a\n * previous call to one of the JPEG compression functions, then `*jpegSize` is\n * also ignored.  Upon return, `*jpegSize` will contain the size of the JPEG\n * image (in bytes.)\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr()\n * and #tj3GetErrorCode().)\n */\nDLLEXPORT int tj3CompressFromYUV8(tjhandle handle,\n                                  const unsigned char *srcBuf, int width,\n                                  int align, int height,\n                                  unsigned char **jpegBuf, size_t *jpegSize);\n\n\n/**\n * Encode an 8-bit-per-sample packed-pixel RGB or grayscale image into separate\n * 8-bit-per-sample Y, U (Cb), and V (Cr) image planes.  This function performs\n * color conversion and downsampling (which are accelerated in the\n * libjpeg-turbo implementation) but does not execute any of the other steps in\n * the JPEG compression process.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * compression\n *\n * @param srcBuf pointer to a buffer containing a packed-pixel RGB or grayscale\n * source image to be encoded.  This buffer should normally be `pitch * height`\n * bytes in size.  However, you can also use this parameter to encode from a\n * specific region of a larger buffer.\n *\n *\n * @param width width (in pixels) of the source image\n *\n * @param pitch bytes per row in the source image.  Normally this should be\n * <tt>width * #tjPixelSize[pixelFormat]</tt>, if the image is unpadded.\n * (Setting this parameter to 0 is the equivalent of setting it to\n * <tt>width * #tjPixelSize[pixelFormat]</tt>.)  However, you can also use this\n * parameter to specify the row alignment/padding of the source image, to skip\n * rows, or to encode from a specific region of a larger packed-pixel image.\n *\n * @param height height (in pixels) of the source image\n *\n * @param pixelFormat pixel format of the source image (see @ref TJPF\n * \"Pixel formats\".)\n *\n * @param dstPlanes an array of pointers to Y, U (Cb), and V (Cr) image planes\n * (or just a Y plane, if generating a grayscale image) that will receive the\n * encoded image.  These planes can be contiguous or non-contiguous in memory.\n * Use #tj3YUVPlaneSize() to determine the appropriate size for each plane\n * based on the image width, height, strides, and level of chrominance\n * subsampling (see #TJPARAM_SUBSAMP.)  Refer to @ref YUVnotes\n * \"YUV Image Format Notes\" for more details.\n *\n * @param strides an array of integers, each specifying the number of bytes per\n * row in the corresponding plane of the YUV image.  Setting the stride for any\n * plane to 0 is the same as setting it to the plane width (see @ref YUVnotes\n * \"YUV Image Format Notes\".)  If `strides` is NULL, then the strides for all\n * planes will be set to their respective plane widths.  You can adjust the\n * strides in order to add an arbitrary amount of row padding to each plane or\n * to encode an RGB or grayscale image into a subregion of a larger planar YUV\n * image.\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr()\n * and #tj3GetErrorCode().)\n */\nDLLEXPORT int tj3EncodeYUVPlanes8(tjhandle handle, const unsigned char *srcBuf,\n                                  int width, int pitch, int height,\n                                  int pixelFormat, unsigned char **dstPlanes,\n                                  int *strides);\n\n\n/**\n * Encode an 8-bit-per-sample packed-pixel RGB or grayscale image into an\n * 8-bit-per-sample unified planar YUV image.  This function performs color\n * conversion and downsampling (which are accelerated in the libjpeg-turbo\n * implementation) but does not execute any of the other steps in the JPEG\n * compression process.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * compression\n *\n * @param srcBuf pointer to a buffer containing a packed-pixel RGB or grayscale\n * source image to be encoded.  This buffer should normally be `pitch * height`\n * bytes in size.  However, you can also use this parameter to encode from a\n * specific region of a larger buffer.\n *\n * @param width width (in pixels) of the source image\n *\n * @param pitch bytes per row in the source image.  Normally this should be\n * <tt>width * #tjPixelSize[pixelFormat]</tt>, if the image is unpadded.\n * (Setting this parameter to 0 is the equivalent of setting it to\n * <tt>width * #tjPixelSize[pixelFormat]</tt>.)  However, you can also use this\n * parameter to specify the row alignment/padding of the source image, to skip\n * rows, or to encode from a specific region of a larger packed-pixel image.\n *\n * @param height height (in pixels) of the source image\n *\n * @param pixelFormat pixel format of the source image (see @ref TJPF\n * \"Pixel formats\".)\n *\n * @param dstBuf pointer to a buffer that will receive the unified planar YUV\n * image.  Use #tj3YUVBufSize() to determine the appropriate size for this\n * buffer based on the image width, height, row alignment, and level of\n * chrominance subsampling (see #TJPARAM_SUBSAMP.)  The Y, U (Cb), and V (Cr)\n * image planes will be stored sequentially in the buffer.  (Refer to\n * @ref YUVnotes \"YUV Image Format Notes\".)\n *\n * @param align row alignment (in bytes) of the YUV image (must be a power of\n * 2.)  Setting this parameter to n will cause each row in each plane of the\n * YUV image to be padded to the nearest multiple of n bytes (1 = unpadded.)\n * To generate images suitable for X Video, `align` should be set to 4.\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr()\n * and #tj3GetErrorCode().)\n */\nDLLEXPORT int tj3EncodeYUV8(tjhandle handle, const unsigned char *srcBuf,\n                            int width, int pitch, int height, int pixelFormat,\n                            unsigned char *dstBuf, int align);\n\n\n/**\n * Retrieve information about a JPEG image without decompressing it, or prime\n * the decompressor with quantization and Huffman tables.  If a JPEG image is\n * passed to this function, then the @ref TJPARAM \"parameters\" that describe\n * the JPEG image will be set when the function returns.  If a JPEG image is\n * passed to this function and #TJPARAM_SAVEMARKERS is set to `2` or `4`, then\n * the ICC profile (if any) will be extracted from the JPEG image.\n * (#tj3GetICCProfile() can then be used to retrieve the profile.)\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * decompression\n *\n * @param jpegBuf pointer to a byte buffer containing a JPEG image or an\n * \"abbreviated table specification\" (AKA \"tables-only\") datastream.  Passing a\n * tables-only datastream to this function primes the decompressor with\n * quantization and Huffman tables that can be used when decompressing\n * subsequent \"abbreviated image\" datastreams.  This is useful, for instance,\n * when decompressing video streams in which all frames share the same\n * quantization and Huffman tables.\n *\n * @param jpegSize size of the JPEG image or tables-only datastream (in bytes)\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr()\n * and #tj3GetErrorCode().)\n */\nDLLEXPORT int tj3DecompressHeader(tjhandle handle,\n                                  const unsigned char *jpegBuf,\n                                  size_t jpegSize);\n\n\n/**\n * Retrieve the ICC (International Color Consortium) color management profile\n * (if any) that was previously extracted from a JPEG image.\n *\n * @note To extract the ICC profile from a JPEG image, call\n * #tj3DecompressHeader() with #TJPARAM_SAVEMARKERS set to `2` or `4`.  Once\n * the ICC profile is retrieved, it must be re-extracted before it can be\n * retrieved again.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * decompression\n *\n * @param iccBuf address of a pointer to a byte buffer.  Upon return:\n * - If `iccBuf` is not NULL and there is an ICC profile to retrieve, then\n * `*iccBuf` will point to a byte buffer containing the ICC profile.  This\n * buffer should be freed using #tj3Free().\n * - If `iccBuf` is not NULL and there is no ICC profile to retrieve, then\n * `*iccBuf` will be NULL.\n * - If `iccBuf` is NULL, then only the ICC profile size will be retrieved, and\n * the ICC profile can be retrieved later.\n *\n * @param iccSize address of a size_t variable.  Upon return, the variable will\n * contain the ICC profile size (or 0 if there is no ICC profile to retrieve.)\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr()\n * and #tj3GetErrorCode().)\n */\nDLLEXPORT int tj3GetICCProfile(tjhandle handle, unsigned char **iccBuf,\n                               size_t *iccSize);\n\n\n/**\n * Returns a list of fractional scaling factors that the JPEG decompressor\n * supports.\n *\n * @param numScalingFactors pointer to an integer variable that will receive\n * the number of elements in the list\n *\n * @return a pointer to a list of fractional scaling factors, or NULL if an\n * error is encountered (see #tj3GetErrorStr().)\n */\nDLLEXPORT tjscalingfactor *tj3GetScalingFactors(int *numScalingFactors);\n\n\n/**\n * Set the scaling factor for subsequent lossy decompression operations.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * decompression\n *\n * @param scalingFactor #tjscalingfactor structure that specifies a fractional\n * scaling factor that the decompressor supports (see #tj3GetScalingFactors()),\n * or <tt>#TJUNSCALED</tt> for no scaling.  Decompression scaling is a function\n * of the IDCT algorithm, so scaling factors are generally limited to multiples\n * of 1/8.  If the entire JPEG image will be decompressed, then the width and\n * height of the scaled destination image can be determined by calling\n * #TJSCALED() with the JPEG width and height (see #TJPARAM_JPEGWIDTH and\n * #TJPARAM_JPEGHEIGHT) and the specified scaling factor.  When decompressing\n * into a planar YUV image, an intermediate buffer copy will be performed if\n * the width or height of the scaled destination image is not an even multiple\n * of the iMCU size (see #tjMCUWidth and #tjMCUHeight.)  Note that\n * decompression scaling is not available (and the specified scaling factor is\n * ignored) when decompressing lossless JPEG images (see #TJPARAM_LOSSLESS),\n * since the IDCT algorithm is not used with those images.  Note also that\n * #TJPARAM_FASTDCT is ignored when decompression scaling is enabled.\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr().)\n */\nDLLEXPORT int tj3SetScalingFactor(tjhandle handle,\n                                  tjscalingfactor scalingFactor);\n\n\n/**\n * Set the cropping region for partially decompressing a lossy JPEG image into\n * a packed-pixel image\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * decompression\n *\n * @param croppingRegion #tjregion structure that specifies a subregion of the\n * JPEG image to decompress, or <tt>#TJUNCROPPED</tt> for no cropping.  The\n * left boundary of the cropping region must be evenly divisible by the scaled\n * iMCU width-- <tt>#TJSCALED(#tjMCUWidth[subsamp], scalingFactor)</tt>, where\n * `subsamp` is the level of chrominance subsampling in the JPEG image (see\n * #TJPARAM_SUBSAMP) and `scalingFactor` is the decompression scaling factor\n * (see #tj3SetScalingFactor().)  The cropping region should be specified\n * relative to the scaled image dimensions.  Unless `croppingRegion` is\n * <tt>#TJUNCROPPED</tt>, the JPEG header must be read (see\n * #tj3DecompressHeader()) prior to calling this function.\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr().)\n */\nDLLEXPORT int tj3SetCroppingRegion(tjhandle handle, tjregion croppingRegion);\n\n\n/**\n * Decompress a JPEG image with 2 to 8 bits of data precision per sample into a\n * packed-pixel RGB, grayscale, or CMYK image with the same data precision.\n * The @ref TJPARAM \"parameters\" that describe the JPEG image will be set when\n * this function returns.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * decompression\n *\n * @param jpegBuf pointer to a byte buffer containing the JPEG image to\n * decompress\n *\n * @param jpegSize size of the JPEG image (in bytes)\n *\n * @param dstBuf pointer to a buffer that will receive the packed-pixel\n * decompressed image.  This buffer should normally be\n * `pitch * destinationHeight` samples in size.  However, you can also use this\n * parameter to decompress into a specific region of a larger buffer.  NOTE:\n * If the JPEG image is lossy, then `destinationHeight` is either the scaled\n * JPEG height (see #TJSCALED(), #TJPARAM_JPEGHEIGHT, and\n * #tj3SetScalingFactor()) or the height of the cropping region (see\n * #tj3SetCroppingRegion().)  If the JPEG image is lossless, then\n * `destinationHeight` is the JPEG height.\n *\n * @param pitch samples per row in the destination image.  Normally this should\n * be set to <tt>destinationWidth * #tjPixelSize[pixelFormat]</tt>, if the\n * destination image should be unpadded.  (Setting this parameter to 0 is the\n * equivalent of setting it to\n * <tt>destinationWidth * #tjPixelSize[pixelFormat]</tt>.)  However, you can\n * also use this parameter to specify the row alignment/padding of the\n * destination image, to skip rows, or to decompress into a specific region of\n * a larger buffer.  NOTE: If the JPEG image is lossy, then `destinationWidth`\n * is either the scaled JPEG width (see #TJSCALED(), #TJPARAM_JPEGWIDTH, and\n * #tj3SetScalingFactor()) or the width of the cropping region (see\n * #tj3SetCroppingRegion().)  If the JPEG image is lossless, then\n * `destinationWidth` is the JPEG width.\n *\n * @param pixelFormat pixel format of the destination image (see @ref\n * TJPF \"Pixel formats\".)\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr()\n * and #tj3GetErrorCode().)\n */\nDLLEXPORT int tj3Decompress8(tjhandle handle, const unsigned char *jpegBuf,\n                             size_t jpegSize, unsigned char *dstBuf, int pitch,\n                             int pixelFormat);\n\n/**\n * Decompress a JPEG image with 9 to 12 bits of data precision per sample into\n * a packed-pixel RGB, grayscale, or CMYK image with the same data precision.\n *\n * \\details \\copydetails tj3Decompress8()\n */\nDLLEXPORT int tj3Decompress12(tjhandle handle, const unsigned char *jpegBuf,\n                              size_t jpegSize, short *dstBuf, int pitch,\n                              int pixelFormat);\n\n/**\n * Decompress a lossless JPEG image with 13 to 16 bits of data precision per\n * sample into a packed-pixel RGB, grayscale, or CMYK image with the same\n * data precision.\n *\n * \\details \\copydetails tj3Decompress8()\n */\nDLLEXPORT int tj3Decompress16(tjhandle handle, const unsigned char *jpegBuf,\n                              size_t jpegSize, unsigned short *dstBuf,\n                              int pitch, int pixelFormat);\n\n\n/**\n * Decompress an 8-bit-per-sample lossy JPEG image into separate\n * 8-bit-per-sample Y, U (Cb), and V (Cr) image planes.  This function performs\n * JPEG decompression but leaves out the color conversion step, so a planar YUV\n * image is generated instead of a packed-pixel image.  The\n * @ref TJPARAM \"parameters\" that describe the JPEG image will be set when this\n * function returns.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * decompression\n *\n * @param jpegBuf pointer to a byte buffer containing the JPEG image to\n * decompress\n *\n * @param jpegSize size of the JPEG image (in bytes)\n *\n * @param dstPlanes an array of pointers to Y, U (Cb), and V (Cr) image planes\n * (or just a Y plane, if decompressing a grayscale image) that will receive\n * the decompressed image.  These planes can be contiguous or non-contiguous in\n * memory.  Use #tj3YUVPlaneSize() to determine the appropriate size for each\n * plane based on the scaled JPEG width and height (see #TJSCALED(),\n * #TJPARAM_JPEGWIDTH, #TJPARAM_JPEGHEIGHT, and #tj3SetScalingFactor()),\n * strides, and level of chrominance subsampling (see #TJPARAM_SUBSAMP.)  Refer\n * to @ref YUVnotes \"YUV Image Format Notes\" for more details.\n *\n * @param strides an array of integers, each specifying the number of bytes per\n * row in the corresponding plane of the YUV image.  Setting the stride for any\n * plane to 0 is the same as setting it to the scaled plane width (see\n * @ref YUVnotes \"YUV Image Format Notes\".)  If `strides` is NULL, then the\n * strides for all planes will be set to their respective scaled plane widths.\n * You can adjust the strides in order to add an arbitrary amount of row\n * padding to each plane or to decompress the JPEG image into a subregion of a\n * larger planar YUV image.\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr()\n * and #tj3GetErrorCode().)\n */\nDLLEXPORT int tj3DecompressToYUVPlanes8(tjhandle handle,\n                                        const unsigned char *jpegBuf,\n                                        size_t jpegSize,\n                                        unsigned char **dstPlanes,\n                                        int *strides);\n\n\n/**\n * Decompress an 8-bit-per-sample lossy JPEG image into an 8-bit-per-sample\n * unified planar YUV image.  This function performs JPEG decompression but\n * leaves out the color conversion step, so a planar YUV image is generated\n * instead of a packed-pixel image.  The @ref TJPARAM \"parameters\" that\n * describe the JPEG image will be set when this function returns.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * decompression\n *\n * @param jpegBuf pointer to a byte buffer containing the JPEG image to\n * decompress\n *\n * @param jpegSize size of the JPEG image (in bytes)\n *\n * @param dstBuf pointer to a buffer that will receive the unified planar YUV\n * decompressed image.  Use #tj3YUVBufSize() to determine the appropriate size\n * for this buffer based on the scaled JPEG width and height (see #TJSCALED(),\n * #TJPARAM_JPEGWIDTH, #TJPARAM_JPEGHEIGHT, and #tj3SetScalingFactor()), row\n * alignment, and level of chrominance subsampling (see #TJPARAM_SUBSAMP.)  The\n * Y, U (Cb), and V (Cr) image planes will be stored sequentially in the\n * buffer.  (Refer to @ref YUVnotes \"YUV Image Format Notes\".)\n *\n * @param align row alignment (in bytes) of the YUV image (must be a power of\n * 2.)  Setting this parameter to n will cause each row in each plane of the\n * YUV image to be padded to the nearest multiple of n bytes (1 = unpadded.)\n * To generate images suitable for X Video, `align` should be set to 4.\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr()\n * and #tj3GetErrorCode().)\n */\nDLLEXPORT int tj3DecompressToYUV8(tjhandle handle,\n                                  const unsigned char *jpegBuf,\n                                  size_t jpegSize,\n                                  unsigned char *dstBuf, int align);\n\n\n/**\n * Decode a set of 8-bit-per-sample Y, U (Cb), and V (Cr) image planes into an\n * 8-bit-per-sample packed-pixel RGB or grayscale image.  This function\n * performs color conversion (which is accelerated in the libjpeg-turbo\n * implementation) but does not execute any of the other steps in the JPEG\n * decompression process.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * decompression\n *\n * @param srcPlanes an array of pointers to Y, U (Cb), and V (Cr) image planes\n * (or just a Y plane, if decoding a grayscale image) that contain a YUV image\n * to be decoded.  These planes can be contiguous or non-contiguous in memory.\n * The size of each plane should match the value returned by #tj3YUVPlaneSize()\n * for the given image width, height, strides, and level of chrominance\n * subsampling (see #TJPARAM_SUBSAMP.)  Refer to @ref YUVnotes\n * \"YUV Image Format Notes\" for more details.\n *\n * @param strides an array of integers, each specifying the number of bytes per\n * row in the corresponding plane of the YUV source image.  Setting the stride\n * for any plane to 0 is the same as setting it to the plane width (see\n * @ref YUVnotes \"YUV Image Format Notes\".)  If `strides` is NULL, then the\n * strides for all planes will be set to their respective plane widths.  You\n * can adjust the strides in order to specify an arbitrary amount of row\n * padding in each plane or to decode a subregion of a larger planar YUV image.\n *\n * @param dstBuf pointer to a buffer that will receive the packed-pixel decoded\n * image.  This buffer should normally be `pitch * height` bytes in size.\n * However, you can also use this parameter to decode into a specific region of\n * a larger buffer.\n *\n * @param width width (in pixels) of the source and destination images\n *\n * @param pitch bytes per row in the destination image.  Normally this should\n * be set to <tt>width * #tjPixelSize[pixelFormat]</tt>, if the destination\n * image should be unpadded.  (Setting this parameter to 0 is the equivalent of\n * setting it to <tt>width * #tjPixelSize[pixelFormat]</tt>.)  However, you can\n * also use this parameter to specify the row alignment/padding of the\n * destination image, to skip rows, or to decode into a specific region of a\n * larger buffer.\n *\n * @param height height (in pixels) of the source and destination images\n *\n * @param pixelFormat pixel format of the destination image (see @ref TJPF\n * \"Pixel formats\".)\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr()\n * and #tj3GetErrorCode().)\n */\nDLLEXPORT int tj3DecodeYUVPlanes8(tjhandle handle,\n                                  const unsigned char * const *srcPlanes,\n                                  const int *strides, unsigned char *dstBuf,\n                                  int width, int pitch, int height,\n                                  int pixelFormat);\n\n\n/**\n * Decode an 8-bit-per-sample unified planar YUV image into an 8-bit-per-sample\n * packed-pixel RGB or grayscale image.  This function performs color\n * conversion (which is accelerated in the libjpeg-turbo implementation) but\n * does not execute any of the other steps in the JPEG decompression process.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * decompression\n *\n * @param srcBuf pointer to a buffer containing a unified planar YUV source\n * image to be decoded.  The size of this buffer should match the value\n * returned by #tj3YUVBufSize() for the given image width, height, row\n * alignment, and level of chrominance subsampling (see #TJPARAM_SUBSAMP.)  The\n * Y, U (Cb), and V (Cr) image planes should be stored sequentially in the\n * source buffer.  (Refer to @ref YUVnotes \"YUV Image Format Notes\".)\n *\n * @param align row alignment (in bytes) of the YUV source image (must be a\n * power of 2.)  Setting this parameter to n indicates that each row in each\n * plane of the YUV source image is padded to the nearest multiple of n bytes\n * (1 = unpadded.)\n *\n * @param dstBuf pointer to a buffer that will receive the packed-pixel decoded\n * image.  This buffer should normally be `pitch * height` bytes in size.\n * However, you can also use this parameter to decode into a specific region of\n * a larger buffer.\n *\n * @param width width (in pixels) of the source and destination images\n *\n * @param pitch bytes per row in the destination image.  Normally this should\n * be set to <tt>width * #tjPixelSize[pixelFormat]</tt>, if the destination\n * image should be unpadded.  (Setting this parameter to 0 is the equivalent of\n * setting it to <tt>width * #tjPixelSize[pixelFormat]</tt>.)  However, you can\n * also use this parameter to specify the row alignment/padding of the\n * destination image, to skip rows, or to decode into a specific region of a\n * larger buffer.\n *\n * @param height height (in pixels) of the source and destination images\n *\n * @param pixelFormat pixel format of the destination image (see @ref TJPF\n * \"Pixel formats\".)\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr()\n * and #tj3GetErrorCode().)\n */\nDLLEXPORT int tj3DecodeYUV8(tjhandle handle, const unsigned char *srcBuf,\n                            int align, unsigned char *dstBuf, int width,\n                            int pitch, int height, int pixelFormat);\n\n\n/**\n * The maximum size of the buffer (in bytes) required to hold a JPEG image\n * transformed with the given transform parameters and/or cropping region.\n * This function is a wrapper for #tj3JPEGBufSize() that takes into account\n * cropping, transposition of the width and height (which affects the\n * destination image dimensions and level of chrominance subsampling),\n * grayscale conversion, and the ICC profile (if any) that was previously\n * associated with the TurboJPEG instance (see #tj3SetICCProfile()) or\n * extracted from the source image (see #tj3GetICCProfile() and\n * #TJPARAM_SAVEMARKERS.)  The JPEG header must be read (see\n * tj3DecompressHeader()) prior to calling this function.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * lossless transformation\n *\n * @param transform pointer to a #tjtransform structure that specifies the\n * transform parameters and/or cropping region for the JPEG image.\n *\n * @return the maximum size of the buffer (in bytes) required to hold the\n * transformed image, or 0 if an error occurred (see #tj3GetErrorStr() and\n * #tj3GetErrorCode().)\n */\nDLLEXPORT size_t tj3TransformBufSize(tjhandle handle,\n                                     const tjtransform *transform);\n\n\n/**\n * Losslessly transform a JPEG image into another JPEG image.  Lossless\n * transforms work by moving the raw DCT coefficients from one JPEG image\n * structure to another without altering the values of the coefficients.  While\n * this is typically faster than decompressing the image, transforming it, and\n * re-compressing it, lossless transforms are not free.  Each lossless\n * transform requires reading and performing entropy decoding on all of the\n * coefficients in the source image, regardless of the size of the destination\n * image.  Thus, this function provides a means of generating multiple\n * transformed images from the same source or applying multiple transformations\n * simultaneously, in order to eliminate the need to read the source\n * coefficients multiple times.\n *\n * @param handle handle to a TurboJPEG instance that has been initialized for\n * lossless transformation\n *\n * @param jpegBuf pointer to a byte buffer containing the JPEG source image to\n * transform\n *\n * @param jpegSize size of the JPEG source image (in bytes)\n *\n * @param n the number of transformed JPEG images to generate\n *\n * @param dstBufs pointer to an array of n byte buffers.  `dstBufs[i]` will\n * receive a JPEG image that has been transformed using the parameters in\n * `transforms[i]`.  TurboJPEG has the ability to reallocate the JPEG\n * destination buffer to accommodate the size of the transformed JPEG image.\n * Thus, you can choose to:\n * -# pre-allocate the JPEG destination buffer with an arbitrary size using\n * #tj3Alloc() and let TurboJPEG grow the buffer as needed,\n * -# set `dstBufs[i]` to NULL to tell TurboJPEG to allocate the buffer for\n * you, or\n * -# pre-allocate the buffer to a \"worst case\" size determined by calling\n * #tj3TransformBufSize().  Under normal circumstances, this should ensure that\n * the buffer never has to be re-allocated.  (Setting #TJPARAM_NOREALLOC\n * guarantees that it won't be.  However, if the source image has a large\n * amount of embedded Exif data, then the transformed JPEG image may be larger\n * than the worst-case size.  #TJPARAM_NOREALLOC cannot be used in that case\n * unless the embedded data is discarded using #TJXOPT_COPYNONE or\n * #TJPARAM_SAVEMARKERS.)\n * .\n * Unless you have set #TJPARAM_NOREALLOC, you should always check `dstBufs[i]`\n * upon return from this function, as it may have changed.\n *\n * @param dstSizes pointer to an array of n size_t variables that will receive\n * the actual sizes (in bytes) of each transformed JPEG image.  If `dstBufs[i]`\n * points to a pre-allocated buffer, then `dstSizes[i]` should be set to the\n * size of the buffer.  Otherwise, `dstSizes[i]` is ignored.  Upon return,\n * `dstSizes[i]` will contain the size of the transformed JPEG image (in\n * bytes.)\n *\n * @param transforms pointer to an array of n #tjtransform structures, each of\n * which specifies the transform parameters and/or cropping region for the\n * corresponding transformed JPEG image.\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr()\n * and #tj3GetErrorCode().)\n */\nDLLEXPORT int tj3Transform(tjhandle handle, const unsigned char *jpegBuf,\n                           size_t jpegSize, int n, unsigned char **dstBufs,\n                           size_t *dstSizes, const tjtransform *transforms);\n\n\n/**\n * Load a packed-pixel image with 2 to 8 bits of data precision per sample from\n * disk into memory.\n *\n * @param handle handle to a TurboJPEG instance\n *\n * @param filename name of a file containing a packed-pixel image in Windows\n * BMP or PBMPLUS (PPM/PGM) format.  Windows BMP files require 8-bit-per-sample\n * data precision.  When loading a PBMPLUS file, the target data precision\n * (from 2 to 8 bits per sample) can be specified using #TJPARAM_PRECISION and\n * defaults to 8 if #TJPARAM_PRECISION is unset or out of range.  If the data\n * precision of the PBMPLUS file does not match the target data precision, then\n * upconverting or downconverting will be performed.\n *\n * @param width pointer to an integer variable that will receive the width (in\n * pixels) of the packed-pixel image\n *\n * @param align row alignment (in samples) of the packed-pixel buffer to be\n * returned (must be a power of 2.)  Setting this parameter to n will cause all\n * rows in the buffer to be padded to the nearest multiple of n samples\n * (1 = unpadded.)\n *\n * @param height pointer to an integer variable that will receive the height\n * (in pixels) of the packed-pixel image\n *\n * @param pixelFormat pointer to an integer variable that specifies or will\n * receive the pixel format of the packed-pixel buffer.  The behavior of this\n * function varies depending on the value of `*pixelFormat` passed to the\n * function:\n * - @ref TJPF_UNKNOWN : The packed-pixel buffer returned by this function will\n * use the most optimal pixel format for the file type, and `*pixelFormat` will\n * contain the ID of that pixel format upon successful return from this\n * function.\n * - @ref TJPF_GRAY : Only PGM files and 8-bit-per-pixel BMP files with a\n * grayscale colormap can be loaded.\n * - @ref TJPF_CMYK : The RGB or grayscale pixels stored in the file will be\n * converted using a quick & dirty algorithm that is suitable only for testing\n * purposes.  (Proper conversion between CMYK and other formats requires a\n * color management system.)\n * - Other @ref TJPF \"pixel formats\" : The packed-pixel buffer will use the\n * specified pixel format, and pixel format conversion will be performed if\n * necessary.\n *\n * @return a pointer to a newly-allocated buffer containing the packed-pixel\n * image, converted to the chosen pixel format and with the chosen row\n * alignment, or NULL if an error occurred (see #tj3GetErrorStr().)  This\n * buffer should be freed using #tj3Free().\n */\nDLLEXPORT unsigned char *tj3LoadImage8(tjhandle handle, const char *filename,\n                                       int *width, int align, int *height,\n                                       int *pixelFormat);\n\n/**\n * Load a packed-pixel image with 9 to 12 bits of data precision per sample\n * from disk into memory.\n *\n * @param handle handle to a TurboJPEG instance\n *\n * @param filename name of a file containing a packed-pixel image in PBMPLUS\n * (PPM/PGM) format.  The target data precision (from 9 to 12 bits per sample)\n * can be specified using #TJPARAM_PRECISION and defaults to 12 if\n * #TJPARAM_PRECISION is unset or out of range.  If the data precision of the\n * PBMPLUS file does not match the target data precision, then upconverting or\n * downconverting will be performed.\n *\n * @param width pointer to an integer variable that will receive the width (in\n * pixels) of the packed-pixel image\n *\n * @param align row alignment (in samples) of the packed-pixel buffer to be\n * returned (must be a power of 2.)  Setting this parameter to n will cause all\n * rows in the buffer to be padded to the nearest multiple of n samples\n * (1 = unpadded.)\n *\n * @param height pointer to an integer variable that will receive the height\n * (in pixels) of the packed-pixel image\n *\n * @param pixelFormat pointer to an integer variable that specifies or will\n * receive the pixel format of the packed-pixel buffer.  The behavior of this\n * function will vary depending on the value of `*pixelFormat` passed to the\n * function:\n * - @ref TJPF_UNKNOWN : The packed-pixel buffer returned by this function will\n * use the most optimal pixel format for the file type, and `*pixelFormat` will\n * contain the ID of that pixel format upon successful return from this\n * function.\n * - @ref TJPF_GRAY : Only PGM files can be loaded.\n * - @ref TJPF_CMYK : The RGB or grayscale pixels stored in the file will be\n * converted using a quick & dirty algorithm that is suitable only for testing\n * purposes.  (Proper conversion between CMYK and other formats requires a\n * color management system.)\n * - Other @ref TJPF \"pixel formats\" : The packed-pixel buffer will use the\n * specified pixel format, and pixel format conversion will be performed if\n * necessary.\n *\n * @return a pointer to a newly-allocated buffer containing the packed-pixel\n * image, converted to the chosen pixel format and with the chosen row\n * alignment, or NULL if an error occurred (see #tj3GetErrorStr().)  This\n * buffer should be freed using #tj3Free().\n */\nDLLEXPORT short *tj3LoadImage12(tjhandle handle, const char *filename,\n                                int *width, int align, int *height,\n                                int *pixelFormat);\n\n/**\n * Load a packed-pixel image with 13 to 16 bits of data precision per sample\n * from disk into memory.\n *\n * @param handle handle to a TurboJPEG instance\n *\n * @param filename name of a file containing a packed-pixel image in PBMPLUS\n * (PPM/PGM) format.  The target data precision (from 13 to 16 bits per sample)\n * can be specified using #TJPARAM_PRECISION and defaults to 16 if\n * #TJPARAM_PRECISION is unset or out of range.  If the data precision of the\n * PBMPLUS file does not match the target data precision, then upconverting or\n * downconverting will be performed.\n *\n * @param width pointer to an integer variable that will receive the width (in\n * pixels) of the packed-pixel image\n *\n * @param align row alignment (in samples) of the packed-pixel buffer to be\n * returned (must be a power of 2.)  Setting this parameter to n will cause all\n * rows in the buffer to be padded to the nearest multiple of n samples\n * (1 = unpadded.)\n *\n * @param height pointer to an integer variable that will receive the height\n * (in pixels) of the packed-pixel image\n *\n * @param pixelFormat pointer to an integer variable that specifies or will\n * receive the pixel format of the packed-pixel buffer.  The behavior of this\n * function will vary depending on the value of `*pixelFormat` passed to the\n * function:\n * - @ref TJPF_UNKNOWN : The packed-pixel buffer returned by this function will\n * use the most optimal pixel format for the file type, and `*pixelFormat` will\n * contain the ID of that pixel format upon successful return from this\n * function.\n * - @ref TJPF_GRAY : Only PGM files can be loaded.\n * - @ref TJPF_CMYK : The RGB or grayscale pixels stored in the file will be\n * converted using a quick & dirty algorithm that is suitable only for testing\n * purposes.  (Proper conversion between CMYK and other formats requires a\n * color management system.)\n * - Other @ref TJPF \"pixel formats\" : The packed-pixel buffer will use the\n * specified pixel format, and pixel format conversion will be performed if\n * necessary.\n *\n * @return a pointer to a newly-allocated buffer containing the packed-pixel\n * image, converted to the chosen pixel format and with the chosen row\n * alignment, or NULL if an error occurred (see #tj3GetErrorStr().)  This\n * buffer should be freed using #tj3Free().\n */\nDLLEXPORT unsigned short *tj3LoadImage16(tjhandle handle, const char *filename,\n                                         int *width, int align, int *height,\n                                         int *pixelFormat);\n\n\n/**\n * Save a packed-pixel image with 2 to 8 bits of data precision per sample from\n * memory to disk.\n *\n * @param handle handle to a TurboJPEG instance\n *\n * @param filename name of a file to which to save the packed-pixel image.  The\n * image will be stored in Windows BMP or PBMPLUS (PPM/PGM) format, depending\n * on the file extension.  Windows BMP files require 8-bit-per-sample data\n * precision.  When saving a PBMPLUS file, the source data precision (from 2 to\n * 8 bits per sample) can be specified using #TJPARAM_PRECISION and defaults to\n * 8 if #TJPARAM_PRECISION is unset or out of range.\n *\n * @param buffer pointer to a buffer containing a packed-pixel RGB, grayscale,\n * or CMYK image to be saved\n *\n * @param width width (in pixels) of the packed-pixel image\n *\n * @param pitch samples per row in the packed-pixel image.  Setting this\n * parameter to 0 is the equivalent of setting it to\n * <tt>width * #tjPixelSize[pixelFormat]</tt>.\n *\n * @param height height (in pixels) of the packed-pixel image\n *\n * @param pixelFormat pixel format of the packed-pixel image (see @ref TJPF\n * \"Pixel formats\".)  If this parameter is set to @ref TJPF_GRAY, then the\n * image will be stored in PGM or 8-bit-per-pixel (indexed color) BMP format.\n * Otherwise, the image will be stored in PPM or 24-bit-per-pixel BMP format.\n * If this parameter is set to @ref TJPF_CMYK, then the CMYK pixels will be\n * converted to RGB using a quick & dirty algorithm that is suitable only for\n * testing purposes.  (Proper conversion between CMYK and other formats\n * requires a color management system.)\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr().)\n */\nDLLEXPORT int tj3SaveImage8(tjhandle handle, const char *filename,\n                            const unsigned char *buffer, int width, int pitch,\n                            int height, int pixelFormat);\n\n/**\n * Save a packed-pixel image with 9 to 12 bits of data precision per sample\n * from memory to disk.\n *\n * @param handle handle to a TurboJPEG instance\n *\n * @param filename name of a file to which to save the packed-pixel image,\n * which will be stored in PBMPLUS (PPM/PGM) format.  The source data precision\n * (from 9 to 12 bits per sample) can be specified using #TJPARAM_PRECISION and\n * defaults to 12 if #TJPARAM_PRECISION is unset or out of range.\n *\n * @param buffer pointer to a buffer containing a packed-pixel RGB, grayscale,\n * or CMYK image to be saved\n *\n * @param width width (in pixels) of the packed-pixel image\n *\n * @param pitch samples per row in the packed-pixel image.  Setting this\n * parameter to 0 is the equivalent of setting it to\n * <tt>width * #tjPixelSize[pixelFormat]</tt>.\n *\n * @param height height (in pixels) of the packed-pixel image\n *\n * @param pixelFormat pixel format of the packed-pixel image (see @ref TJPF\n * \"Pixel formats\".)  If this parameter is set to @ref TJPF_GRAY, then the\n * image will be stored in PGM format.  Otherwise, the image will be stored in\n * PPM format.  If this parameter is set to @ref TJPF_CMYK, then the CMYK\n * pixels will be converted to RGB using a quick & dirty algorithm that is\n * suitable only for testing purposes.  (Proper conversion between CMYK and\n * other formats requires a color management system.)\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr().)\n */\nDLLEXPORT int tj3SaveImage12(tjhandle handle, const char *filename,\n                             const short *buffer, int width, int pitch,\n                             int height, int pixelFormat);\n\n/**\n * Save a packed-pixel image with 13 to 16 bits of data precision per sample\n * from memory to disk.\n *\n * @param handle handle to a TurboJPEG instance\n *\n * @param filename name of a file to which to save the packed-pixel image,\n * which will be stored in PBMPLUS (PPM/PGM) format.  The source data precision\n * (from 13 to 16 bits per sample) can be specified using #TJPARAM_PRECISION\n * and defaults to 16 if #TJPARAM_PRECISION is unset or out of range.\n *\n * @param buffer pointer to a buffer containing a packed-pixel RGB, grayscale,\n * or CMYK image to be saved\n *\n * @param width width (in pixels) of the packed-pixel image\n *\n * @param pitch samples per row in the packed-pixel image.  Setting this\n * parameter to 0 is the equivalent of setting it to\n * <tt>width * #tjPixelSize[pixelFormat]</tt>.\n *\n * @param height height (in pixels) of the packed-pixel image\n *\n * @param pixelFormat pixel format of the packed-pixel image (see @ref TJPF\n * \"Pixel formats\".)  If this parameter is set to @ref TJPF_GRAY, then the\n * image will be stored in PGM format.  Otherwise, the image will be stored in\n * PPM format.  If this parameter is set to @ref TJPF_CMYK, then the CMYK\n * pixels will be converted to RGB using a quick & dirty algorithm that is\n * suitable only for testing purposes.  (Proper conversion between CMYK and\n * other formats requires a color management system.)\n *\n * @return 0 if successful, or -1 if an error occurred (see #tj3GetErrorStr().)\n */\nDLLEXPORT int tj3SaveImage16(tjhandle handle, const char *filename,\n                             const unsigned short *buffer, int width,\n                             int pitch, int height, int pixelFormat);\n\n\n/* Backward compatibility functions and macros (nothing to see here) */\n\n/* TurboJPEG 1.0+ */\n\n#define NUMSUBOPT  TJ_NUMSAMP\n#define TJ_444  TJSAMP_444\n#define TJ_422  TJSAMP_422\n#define TJ_420  TJSAMP_420\n#define TJ_411  TJSAMP_420\n#define TJ_GRAYSCALE  TJSAMP_GRAY\n\n#define TJ_BGR  1\n#define TJ_BOTTOMUP  TJFLAG_BOTTOMUP\n#define TJ_FORCEMMX  TJFLAG_FORCEMMX\n#define TJ_FORCESSE  TJFLAG_FORCESSE\n#define TJ_FORCESSE2  TJFLAG_FORCESSE2\n#define TJ_ALPHAFIRST  64\n#define TJ_FORCESSE3  TJFLAG_FORCESSE3\n#define TJ_FASTUPSAMPLE  TJFLAG_FASTUPSAMPLE\n\n#define TJPAD(width)  (((width) + 3) & (~3))\n\nDLLEXPORT unsigned long TJBUFSIZE(int width, int height);\n\nDLLEXPORT int tjCompress(tjhandle handle, unsigned char *srcBuf, int width,\n                         int pitch, int height, int pixelSize,\n                         unsigned char *dstBuf, unsigned long *compressedSize,\n                         int jpegSubsamp, int jpegQual, int flags);\n\nDLLEXPORT int tjDecompress(tjhandle handle, unsigned char *jpegBuf,\n                           unsigned long jpegSize, unsigned char *dstBuf,\n                           int width, int pitch, int height, int pixelSize,\n                           int flags);\n\nDLLEXPORT int tjDecompressHeader(tjhandle handle, unsigned char *jpegBuf,\n                                 unsigned long jpegSize, int *width,\n                                 int *height);\n\nDLLEXPORT int tjDestroy(tjhandle handle);\n\nDLLEXPORT char *tjGetErrorStr(void);\n\nDLLEXPORT tjhandle tjInitCompress(void);\n\nDLLEXPORT tjhandle tjInitDecompress(void);\n\n/* TurboJPEG 1.1+ */\n\n#define TJ_YUV  512\n\nDLLEXPORT unsigned long TJBUFSIZEYUV(int width, int height, int jpegSubsamp);\n\nDLLEXPORT int tjDecompressHeader2(tjhandle handle, unsigned char *jpegBuf,\n                                  unsigned long jpegSize, int *width,\n                                  int *height, int *jpegSubsamp);\n\nDLLEXPORT int tjDecompressToYUV(tjhandle handle, unsigned char *jpegBuf,\n                                unsigned long jpegSize, unsigned char *dstBuf,\n                                int flags);\n\nDLLEXPORT int tjEncodeYUV(tjhandle handle, unsigned char *srcBuf, int width,\n                          int pitch, int height, int pixelSize,\n                          unsigned char *dstBuf, int subsamp, int flags);\n\n/* TurboJPEG 1.2+ */\n\n#define TJFLAG_BOTTOMUP  2\n#define TJFLAG_FORCEMMX  8\n#define TJFLAG_FORCESSE  16\n#define TJFLAG_FORCESSE2  32\n#define TJFLAG_FORCESSE3  128\n#define TJFLAG_FASTUPSAMPLE  256\n#define TJFLAG_NOREALLOC  1024\n\nDLLEXPORT unsigned char *tjAlloc(int bytes);\n\nDLLEXPORT unsigned long tjBufSize(int width, int height, int jpegSubsamp);\n\nDLLEXPORT unsigned long tjBufSizeYUV(int width, int height, int subsamp);\n\nDLLEXPORT int tjCompress2(tjhandle handle, const unsigned char *srcBuf,\n                          int width, int pitch, int height, int pixelFormat,\n                          unsigned char **jpegBuf, unsigned long *jpegSize,\n                          int jpegSubsamp, int jpegQual, int flags);\n\nDLLEXPORT int tjDecompress2(tjhandle handle, const unsigned char *jpegBuf,\n                            unsigned long jpegSize, unsigned char *dstBuf,\n                            int width, int pitch, int height, int pixelFormat,\n                            int flags);\n\nDLLEXPORT int tjEncodeYUV2(tjhandle handle, unsigned char *srcBuf, int width,\n                           int pitch, int height, int pixelFormat,\n                           unsigned char *dstBuf, int subsamp, int flags);\n\nDLLEXPORT void tjFree(unsigned char *buffer);\n\nDLLEXPORT tjscalingfactor *tjGetScalingFactors(int *numscalingfactors);\n\nDLLEXPORT tjhandle tjInitTransform(void);\n\nDLLEXPORT int tjTransform(tjhandle handle, const unsigned char *jpegBuf,\n                            unsigned long jpegSize, int n,\n                            unsigned char **dstBufs, unsigned long *dstSizes,\n                            tjtransform *transforms, int flags);\n\n/* TurboJPEG 1.2.1+ */\n\n#define TJFLAG_FASTDCT  2048\n#define TJFLAG_ACCURATEDCT  4096\n\n/* TurboJPEG 1.4+ */\n\nDLLEXPORT unsigned long tjBufSizeYUV2(int width, int align, int height,\n                                      int subsamp);\n\nDLLEXPORT int tjCompressFromYUV(tjhandle handle, const unsigned char *srcBuf,\n                                int width, int align, int height, int subsamp,\n                                unsigned char **jpegBuf,\n                                unsigned long *jpegSize, int jpegQual,\n                                int flags);\n\nDLLEXPORT int tjCompressFromYUVPlanes(tjhandle handle,\n                                      const unsigned char **srcPlanes,\n                                      int width, const int *strides,\n                                      int height, int subsamp,\n                                      unsigned char **jpegBuf,\n                                      unsigned long *jpegSize, int jpegQual,\n                                      int flags);\n\nDLLEXPORT int tjDecodeYUV(tjhandle handle, const unsigned char *srcBuf,\n                          int align, int subsamp, unsigned char *dstBuf,\n                          int width, int pitch, int height, int pixelFormat,\n                          int flags);\n\nDLLEXPORT int tjDecodeYUVPlanes(tjhandle handle,\n                                const unsigned char **srcPlanes,\n                                const int *strides, int subsamp,\n                                unsigned char *dstBuf, int width, int pitch,\n                                int height, int pixelFormat, int flags);\n\nDLLEXPORT int tjDecompressHeader3(tjhandle handle,\n                                  const unsigned char *jpegBuf,\n                                  unsigned long jpegSize, int *width,\n                                  int *height, int *jpegSubsamp,\n                                  int *jpegColorspace);\n\nDLLEXPORT int tjDecompressToYUV2(tjhandle handle, const unsigned char *jpegBuf,\n                                 unsigned long jpegSize, unsigned char *dstBuf,\n                                 int width, int align, int height, int flags);\n\nDLLEXPORT int tjDecompressToYUVPlanes(tjhandle handle,\n                                      const unsigned char *jpegBuf,\n                                      unsigned long jpegSize,\n                                      unsigned char **dstPlanes, int width,\n                                      int *strides, int height, int flags);\n\nDLLEXPORT int tjEncodeYUV3(tjhandle handle, const unsigned char *srcBuf,\n                           int width, int pitch, int height, int pixelFormat,\n                           unsigned char *dstBuf, int align, int subsamp,\n                           int flags);\n\nDLLEXPORT int tjEncodeYUVPlanes(tjhandle handle, const unsigned char *srcBuf,\n                                int width, int pitch, int height,\n                                int pixelFormat, unsigned char **dstPlanes,\n                                int *strides, int subsamp, int flags);\n\nDLLEXPORT int tjPlaneHeight(int componentID, int height, int subsamp);\n\nDLLEXPORT unsigned long tjPlaneSizeYUV(int componentID, int width, int stride,\n                                       int height, int subsamp);\n\nDLLEXPORT int tjPlaneWidth(int componentID, int width, int subsamp);\n\n/* TurboJPEG 2.0+ */\n\n#define TJFLAG_STOPONWARNING  8192\n#define TJFLAG_PROGRESSIVE  16384\n\nDLLEXPORT int tjGetErrorCode(tjhandle handle);\n\nDLLEXPORT char *tjGetErrorStr2(tjhandle handle);\n\nDLLEXPORT unsigned char *tjLoadImage(const char *filename, int *width,\n                                     int align, int *height, int *pixelFormat,\n                                     int flags);\n\nDLLEXPORT int tjSaveImage(const char *filename, unsigned char *buffer,\n                          int width, int pitch, int height, int pixelFormat,\n                          int flags);\n\n/* TurboJPEG 2.1+ */\n\n#define TJFLAG_LIMITSCANS  32768\n\n/**\n * @}\n */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "luban/src/main/cpp/turbojpeg_wrapper.cpp",
    "content": "#include <jni.h>\n#include <android/log.h>\n#include <cstring>\n#include \"turbojpeg.h\"\n\n#define LOG_TAG \"TurboJpeg\"\n#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)\n#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)\n\nstatic const char* get_error_string() {\n    return tjGetErrorStr();\n}\n\nextern \"C\" JNIEXPORT jbyteArray JNICALL\nJava_top_zibin_luban_compression_TurboJpegNative_compress(\n    JNIEnv *env,\n    jobject thiz,\n    jbyteArray rgbData,\n    jint width,\n    jint height,\n    jint quality\n) {\n    unsigned long jpegSize = 0;\n    unsigned char* jpegBuf = nullptr;\n    tjhandle handle = nullptr;\n\n    jbyte* inputData = env->GetByteArrayElements(rgbData, nullptr);\n    if (!inputData) {\n        LOGE(\"获取输入数据失败 (Failed to get input data)\");\n        return nullptr;\n    }\n\n    handle = tjInitCompress();\n    if (!handle) {\n        LOGE(\"初始化压缩器失败 (Failed to initialize compressor): %s\", get_error_string());\n        env->ReleaseByteArrayElements(rgbData, inputData, JNI_ABORT);\n        return nullptr;\n    }\n\n    int result = tjCompress2(\n        handle,\n        (unsigned char*)inputData,\n        width,\n        0,\n        height,\n        TJPF_RGB,\n        &jpegBuf,\n        &jpegSize,\n        TJSAMP_444,\n        quality,\n        TJFLAG_FASTDCT\n    );\n\n    env->ReleaseByteArrayElements(rgbData, inputData, JNI_ABORT);\n\n    if (result != 0) {\n        LOGE(\"压缩失败 (Compression failed): %s\", get_error_string());\n        tjDestroy(handle);\n        return nullptr;\n    }\n\n    jbyteArray jpegArray = env->NewByteArray((jsize)jpegSize);\n    if (!jpegArray) {\n        LOGE(\"创建字节数组失败 (Failed to create byte array)\");\n        tjFree(jpegBuf);\n        tjDestroy(handle);\n        return nullptr;\n    }\n\n    env->SetByteArrayRegion(jpegArray, 0, (jsize)jpegSize, (jbyte*)jpegBuf);\n\n    tjFree(jpegBuf);\n    tjDestroy(handle);\n\n    return jpegArray;\n}\n\nextern \"C\" JNIEXPORT jstring JNICALL\nJava_top_zibin_luban_compression_TurboJpegNative_getErrorString(\n    JNIEnv *env,\n    jobject thiz\n) {\n    const char* error = get_error_string();\n    return env->NewStringUTF(error ? error : \"未知错误 (Unknown error)\");\n}\n"
  },
  {
    "path": "luban/src/main/java/top/zibin/luban/algorithm/CompressionCalculator.kt",
    "content": "package top.zibin.luban.algorithm\n\nimport kotlin.math.floor\nimport kotlin.math.max\nimport kotlin.math.min\nimport kotlin.math.sqrt\n\ndata class CompressionTarget(\n    val width: Int,\n    val height: Int,\n    val estimatedSizeKb: Int,\n    val isLongImage: Boolean = false,\n    val targetSizeKb: Int? = null\n)\n\nclass CompressionCalculator {\n    private val baseShort = 1440\n    private val wallLong = 10800\n    private val wallRatio = 0.4\n    private val trapPixels = 40_960_000L\n    private val capPixels = 10_240_000L\n\n    fun calculateTarget(width: Int, height: Int): CompressionTarget {\n        if (width <= 0 || height <= 0) {\n            return CompressionTarget(0, 0, 0)\n        }\n\n        val shortSide = min(width, height)\n        val longSide = max(width, height)\n        val ratio = shortSide.toDouble() / longSide\n        val pixelCount = width.toLong() * height\n\n        var targetShort = baseShort\n        var targetLong = (targetShort / ratio).toInt()\n\n        if (longSide >= wallLong && ratio > wallRatio) {\n            targetLong = baseShort\n            targetShort = (targetLong * ratio).toInt()\n        }\n\n        if (pixelCount > trapPixels) {\n            val trapShort = (shortSide * 0.25).toInt()\n            if (trapShort < targetShort) {\n                targetShort = trapShort\n                targetLong = (targetShort / ratio).toInt()\n            }\n        }\n\n        if (targetShort > shortSide) {\n            targetShort = shortSide\n            targetLong = longSide\n        }\n\n        val currentPixels = targetShort.toLong() * targetLong\n        if (currentPixels > capPixels) {\n            val scale = floor(sqrt(capPixels.toDouble() / currentPixels) * 1000) / 1000.0\n            targetShort = (targetShort * scale).toInt()\n            targetLong = (targetLong * scale).toInt()\n        }\n\n        targetShort = (targetShort / 2) * 2\n        targetLong = (targetLong / 2) * 2\n\n        targetShort = maxOf(2, targetShort)\n        targetLong = maxOf(2, targetLong)\n\n        val (finalW, finalH) = if (width < height) {\n            Pair(targetShort, targetLong)\n        } else {\n            Pair(targetLong, targetShort)\n        }\n\n        val finalPixels = finalW.toLong() * finalH\n\n        val factor = when {\n            finalPixels < 500_000L -> 0.0005\n            finalPixels < 1_000_000L -> 0.00015\n            finalPixels < 3_000_000L -> 0.00011\n            else -> 0.000025\n        }\n\n        var estimatedSize = (finalPixels * factor).toInt()\n        estimatedSize = maxOf(20, estimatedSize)\n\n        if (ratio < 0.2 && estimatedSize < 400) {\n            estimatedSize = maxOf(estimatedSize, 250)\n        }\n\n        val isLongImage = ratio <= 0.5\n        val targetSizeKb = if (isLongImage) estimatedSize else null\n\n        return CompressionTarget(\n            finalW,\n            finalH,\n            estimatedSize,\n            isLongImage,\n            targetSizeKb\n        )\n    }\n}\n"
  },
  {
    "path": "luban/src/main/java/top/zibin/luban/api/CompressionTask.kt",
    "content": "package top.zibin.luban.api\n\n/**\n * 表示一个正在运行的压缩任务。\n *\n * 调用方可以通过该接口取消压缩操作。\n *\n * Represents a running compression task.\n *\n * Allows the caller to cancel the compression operation.\n */\ninterface CompressionTask {\n    /**\n     * 取消当前压缩任务。\n     *\n     * Cancels the compression task.\n     */\n    fun cancel()\n}\n"
  },
  {
    "path": "luban/src/main/java/top/zibin/luban/api/Luban.kt",
    "content": "package top.zibin.luban.api\n\nimport android.content.Context\nimport android.graphics.Bitmap\nimport android.graphics.BitmapFactory\nimport android.net.Uri\nimport kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.async\nimport kotlinx.coroutines.awaitAll\nimport kotlinx.coroutines.coroutineScope\nimport kotlinx.coroutines.withContext\nimport top.zibin.luban.algorithm.CompressionCalculator\nimport top.zibin.luban.algorithm.CompressionTarget\nimport top.zibin.luban.compression.Compressor\nimport top.zibin.luban.compression.JpegCompressor\nimport top.zibin.luban.io.ImageData\nimport top.zibin.luban.io.ImageLoader\nimport java.io.File\nimport java.io.FileOutputStream\n\n/**\n * 图片压缩核心类。\n *\n * 使用 Kotlin 协程实现异步压缩，支持单图与多图压缩。\n *\n * Image compression core class.\n *\n * Uses Kotlin Coroutines for asynchronous compression, supporting both single and multiple image processing.\n *\n * @property compressor 图片压缩实现，默认使用 [JpegCompressor]。\n * The image compressor implementation, defaults to [JpegCompressor].\n\n * @property imageLoader 图片加载实现，默认使用 [ImageLoader]。\n * The image loader implementation, defaults to [ImageLoader].\n \n * @property calculator 压缩参数计算实现，默认使用 [CompressionCalculator]。\n * The compression calculator implementation, defaults to [CompressionCalculator].\n */\nclass Luban @JvmOverloads constructor(\n    private val compressor: Compressor = JpegCompressor(),\n    private val imageLoader: ImageLoader = ImageLoader(),\n    private val calculator: CompressionCalculator = CompressionCalculator()\n) {\n\n    companion object {\n        private val defaultInstance by lazy { Luban() }\n\n        /**\n         * 为 Java 兼容性或流式 API 使用创建一个 Builder。\n         *\n         * Creates a builder for Java compatibility or fluent API usage.\n         *\n         * @param context Android 上下文。\n         * The Android Context.\n         *\n         * @return 一个 [LubanCompat.Builder] 实例。\n         * A [LubanCompat.Builder] instance.\n         */\n        @JvmStatic\n        fun with(context: Context): LubanCompat.Builder {\n            return LubanCompat.Builder(context)\n        }\n\n        /**\n         * 压缩单个 Uri 图片。\n         *\n         * Compresses a single image from a Uri.\n         *\n         * @param context 用于解析 Uri 的上下文。\n         * Context required to resolve the Uri.\n         *\n         * @param input 需要压缩的图片 Uri。\n         * The image Uri to compress.\n         *\n         * @param outputDir 压缩后图片的输出目录，默认为 context.cacheDir。\n         * The directory where the compressed image will be saved, defaults to context.cacheDir.\n         *\n         * @return 包含压缩后 [File] 或异常信息的 [Result]。\n         * A [Result] containing the compressed [File] or the exception if failed.\n         */\n        @JvmOverloads\n        suspend fun compress(context: Context, input: Uri, outputDir: File = context.cacheDir): Result<File> {\n            return defaultInstance.compress(context, input, outputDir)\n        }\n\n        /**\n         * 压缩单个图片文件。\n         *\n         * Compresses a single image file。\n         *\n         * @param input 需要压缩的图片文件。\n         * The image file to compress。\n         *\n         * @param outputDir 压缩后图片的输出目录。\n         * The directory where the compressed image will be saved。\n         *\n         * @return 包含压缩后 [File] 或异常信息的 [Result]。\n         * A [Result] containing the compressed [File] or the exception if failed。\n         */\n        suspend fun compress(input: File, outputDir: File): Result<File> {\n            return defaultInstance.compress(input, outputDir)\n        }\n\n        /**\n         * 将单个图片文件压缩到一个指定输出文件。\n         *\n         * Compresses a single image file to a specific output file.\n         *\n         * @param input 需要压缩的图片文件。\n         * The image file to compress.\n         *\n         * @param output 指定的输出文件。\n         * The specific output file destination.\n         *\n         * @return 包含压缩后 [File] 或异常信息的 [Result]。\n         * A [Result] containing the compressed [File] or the exception if failed.\n         */\n        suspend fun compressToFile(input: File, output: File): Result<File> {\n            return defaultInstance.compressToFile(input, output)\n        }\n\n        /**\n         * 并发压缩多个 Uri 图片。\n         *\n         * Compresses a list of image Uris concurrently.\n         *\n         * @param context 用于解析 Uri 的上下文。\n         * Context required to resolve the Uris.\n         *\n         * @param inputs 需要压缩的 Uri 列表。\n         * The list of image Uris to compress.\n         *\n         * @param outputDir 压缩后图片的输出目录，默认为 context.cacheDir。\n         * The directory where the compressed images will be saved, defaults to context.cacheDir.\n         *\n         * @return [Result] 列表，每个元素包含压缩后 [File] 或异常信息。\n         * A list of [Result]s, each containing the compressed [File] or exception.\n         */\n        @JvmOverloads\n        suspend fun compress(context: Context, inputs: List<Uri>, outputDir: File = context.cacheDir): List<Result<File>> {\n            return defaultInstance.compress(context, inputs, outputDir)\n        }\n\n        /**\n         * 并发压缩多个图片文件。\n         *\n         * Compresses a list of image files concurrently.\n         *\n         * @param inputs 需要压缩的图片文件列表。\n         * The list of image files to compress.\n         *\n         * @param outputDir 压缩后图片的输出目录。\n         * The directory where the compressed images will be saved.\n         *\n         * @return [Result] 列表，每个元素包含压缩后 [File] 或异常信息。\n         * A list of [Result]s, each containing the compressed [File] or exception.\n         */\n        suspend fun compress(inputs: List<File>, outputDir: File): List<Result<File>> {\n            return defaultInstance.compress(inputs, outputDir)\n        }\n    }\n\n    /**\n     * 压缩单个 Uri 图片。\n     *\n     * Compresses a single image from a Uri.\n     *\n     * @param context 用于解析 Uri 的上下文。\n     * Context required to resolve the Uri.\n     *\n     * @param input 需要压缩的图片 Uri。\n     * The image Uri to compress.\n     *\n     * @param outputDir 压缩后图片的输出目录。\n     * The directory where the compressed image will be saved.\n     *\n     * @return 包含压缩后 [File] 或异常信息的 [Result]。\n     * A [Result] containing the compressed [File] or the exception if failed.\n     */\n    suspend fun compress(context: Context, input: Uri, outputDir: File): Result<File> = runCatching {\n        outputDir.mkdirs()\n        val outputFile = generateOutputFileForUri(input, outputDir)\n        compressInternal(context, input, outputFile)\n    }\n\n    /**\n     * 压缩单个图片文件。\n     *\n     * Compresses a single image file.\n     *\n     * @param input 需要压缩的图片文件。\n     * The image file to compress.\n     *\n     * @param outputDir 压缩后图片的输出目录。\n     * The directory where the compressed image will be saved.\n     *\n     * @return 包含压缩后 [File] 或异常信息的 [Result]。\n     * A [Result] containing the compressed [File] or the exception if failed.\n     */\n    suspend fun compress(input: File, outputDir: File): Result<File> = runCatching {\n        val outputFile = generateOutputFile(input, outputDir)\n        compressInternal(input, outputFile)\n    }\n\n    /**\n     * 将单个图片文件压缩到一个指定输出文件。\n     *\n     * Compresses a single image file to a specific output file.\n     *\n     * @param input 需要压缩的图片文件。\n     * The image file to compress.\n     *\n     * @param output 指定的输出文件。\n     * The specific output file destination.\n     *\n     * @return 包含压缩后 [File] 或异常信息的 [Result]。\n     * A [Result] containing the compressed [File] or the exception if failed.\n     */\n    suspend fun compressToFile(input: File, output: File): Result<File> = runCatching {\n        compressInternal(input, output)\n    }\n\n    /**\n     * 并发压缩多个 Uri 图片。\n     *\n     * Compresses a list of image Uris concurrently.\n     *\n     * @param context 用于解析 Uri 的上下文。\n     * Context required to resolve the Uris.\n     *\n     * @param inputs 需要压缩的 Uri 列表。\n     * The list of image Uris to compress.\n     *\n     * @param outputDir 压缩后图片的输出目录。\n     * The directory where the compressed images will be saved.\n     *\n     * @return [Result] 列表，每个元素包含压缩后 [File] 或异常信息。\n     * A list of [Result]s, each containing the compressed [File] or exception.\n     */\n    suspend fun compress(context: Context, inputs: List<Uri>, outputDir: File): List<Result<File>> = coroutineScope {\n        inputs.map { uri ->\n            async { compress(context, uri, outputDir) }\n        }.awaitAll()\n    }\n\n    /**\n     * 并发压缩多个图片文件。\n     *\n     * Compresses a list of image files concurrently.\n     *\n     * @param inputs 需要压缩的图片文件列表。\n     * The list of image files to compress.\n     *\n     * @param outputDir 压缩后图片的输出目录。\n     * The directory where the compressed images will be saved.\n     *\n     * @return [Result] 列表，每个元素包含压缩后 [File] 或异常信息。\n     * A list of [Result]s, each containing the compressed [File] or exception.\n     */\n    suspend fun compress(inputs: List<File>, outputDir: File): List<Result<File>> = coroutineScope {\n        inputs.map { file ->\n            async { compress(file, outputDir) }\n        }.awaitAll()\n    }\n\n    private suspend fun compressInternal(context: Context, input: Uri, output: File): File = withContext(Dispatchers.IO) {\n        val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }\n        context.contentResolver.openInputStream(input)?.use {\n            BitmapFactory.decodeStream(it, null, options)\n        }\n\n        val target = calculator.calculateTarget(options.outWidth, options.outHeight)\n\n        val imageData = imageLoader.loadFromUri(context, input, target.width, target.height)\n        processImage(imageData, output, target, null)\n    }\n\n    private suspend fun compressInternal(input: File, output: File): File = withContext(Dispatchers.IO) {\n        val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }\n        BitmapFactory.decodeFile(input.absolutePath, options)\n\n        val target = calculator.calculateTarget(options.outWidth, options.outHeight)\n\n        val imageData = imageLoader.loadFromFile(input, target.width, target.height)\n        processImage(imageData, output, target, input)\n    }\n\n    private suspend fun processImage(imageData: ImageData, output: File, target: CompressionTarget, originalFile: File?): File = withContext(Dispatchers.IO) {\n        var bitmap = imageData.bitmap\n        try {\n            if (bitmap.config != Bitmap.Config.RGB_565 && bitmap.config != Bitmap.Config.ARGB_8888) {\n                val rgbBitmap = if (bitmap.config == Bitmap.Config.ARGB_8888) {\n                    bitmap.copy(Bitmap.Config.RGB_565, false)\n                } else {\n                    bitmap.copy(Bitmap.Config.ARGB_8888, false)\n                }\n                if (rgbBitmap != bitmap) {\n                    bitmap.recycle()\n                    bitmap = rgbBitmap\n                }\n            }\n\n            val fixedQuality = if (!target.isLongImage) 60 else null\n            val compressedBytes = compressor.compress(bitmap, target.targetSizeKb, fixedQuality)\n\n            val originalSizeBytes = (imageData.fileSizeKb * 1024).toLong()\n            val compressedSizeBytes = compressedBytes.size.toLong()\n\n            output.parentFile?.mkdirs()\n            \n            if (compressedSizeBytes >= originalSizeBytes && originalFile != null && originalFile.exists()) {\n                originalFile.copyTo(output, overwrite = true)\n            } else {\n                FileOutputStream(output).use { fos ->\n                    fos.write(compressedBytes)\n                }\n            }\n\n            output\n        } finally {\n            if (!bitmap.isRecycled) {\n                bitmap.recycle()\n            }\n        }\n    }\n\n    private fun generateOutputFile(inputFile: File, outputDir: File): File {\n        outputDir.mkdirs()\n        val inputName = inputFile.nameWithoutExtension\n        val timestamp = System.currentTimeMillis()\n        return File(outputDir, \"${inputName}_${timestamp}.jpg\")\n    }\n\n    private fun generateOutputFileForUri(uri: Uri, outputDir: File): File {\n        val fileName = uri.lastPathSegment ?: \"compressed\"\n        val nameWithoutExt = fileName.substringBeforeLast(\".\")\n        val timestamp = System.currentTimeMillis()\n        return File(outputDir, \"${nameWithoutExt}_${timestamp}.jpg\")\n    }\n}\n\nsuspend fun File.compressTo(outputDir: File): Result<File> {\n    return Luban.compress(this, outputDir)\n}\n\nsuspend fun File.compressToFile(output: File): Result<File> {\n    return Luban.compressToFile(this, output)\n}\n\nsuspend fun Uri.compressTo(context: Context, outputDir: File = context.cacheDir): Result<File> {\n    return Luban.compress(context, this, outputDir)\n}\n\nsuspend fun List<File>.compressTo(outputDir: File): List<Result<File>> {\n    return Luban.compress(this, outputDir)\n}\n\nsuspend fun List<Uri>.compressTo(context: Context, outputDir: File = context.cacheDir): List<Result<File>> {\n    return Luban.compress(context, this, outputDir)\n}\n\nclass LubanDsl internal constructor(private val context: Context?) {\n    var outputDir: File? = null\n    private val tasks = mutableListOf<suspend () -> Result<File>>()\n    private val batchTasks = mutableListOf<suspend () -> List<Result<File>>>()\n\n    fun compress(input: File): LubanDsl {\n        tasks.add {\n            val currentDir = this@LubanDsl.outputDir\n            if (currentDir != null) {\n                Luban.compress(input, currentDir)\n            } else {\n                Result.failure(IllegalStateException(\"Output directory is not set\"))\n            }\n        }\n        return this\n    }\n\n    fun compress(input: Uri): LubanDsl {\n        val ctx = context ?: throw IllegalStateException(\"Context is required for Uri compression\")\n        tasks.add {\n            val currentDir = this@LubanDsl.outputDir ?: ctx.cacheDir\n            Luban.compress(ctx, input, currentDir)\n        }\n        return this\n    }\n\n    @JvmName(\"compressFiles\")\n    fun compress(inputs: List<File>): LubanDsl {\n        batchTasks.add {\n            val currentDir = this@LubanDsl.outputDir\n            if (currentDir != null) {\n                Luban.compress(inputs, currentDir)\n            } else {\n                inputs.map { Result.failure<File>(IllegalStateException(\"Output directory is not set\")) }\n            }\n        }\n        return this\n    }\n\n    @JvmName(\"compressUris\")\n    fun compress(inputs: List<Uri>): LubanDsl {\n        val ctx = context ?: throw IllegalStateException(\"Context is required for Uri compression\")\n        batchTasks.add {\n            val currentDir = this@LubanDsl.outputDir ?: ctx.cacheDir\n            Luban.compress(ctx, inputs, currentDir)\n        }\n        return this\n    }\n\n    suspend fun execute(): List<Result<File>> {\n        val results = mutableListOf<Result<File>>()\n        tasks.forEach { task ->\n            results.add(task())\n        }\n        batchTasks.forEach { batchTask ->\n            results.addAll(batchTask())\n        }\n        return results\n    }\n}\n\nsuspend fun luban(context: Context, block: LubanDsl.() -> Unit): List<Result<File>> {\n    return LubanDsl(context).apply(block).execute()\n}\n\nsuspend fun luban(block: LubanDsl.() -> Unit): List<Result<File>> {\n    return LubanDsl(null).apply(block).execute()\n}\n"
  },
  {
    "path": "luban/src/main/java/top/zibin/luban/api/LubanCompat.kt",
    "content": "package top.zibin.luban.api\n\nimport android.content.Context\nimport android.net.Uri\nimport androidx.lifecycle.Lifecycle\nimport androidx.lifecycle.LifecycleEventObserver\nimport androidx.lifecycle.LifecycleOwner\nimport kotlinx.coroutines.CoroutineScope\nimport kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.Job\nimport kotlinx.coroutines.SupervisorJob\nimport kotlinx.coroutines.cancel\nimport kotlinx.coroutines.launch\nimport java.io.File\n\n/**\n * 面向 Java 用户或偏好构建器模式 / 回调式 API 的兼容层。\n *\n * 该类封装了基于协程实现的 [Luban] 压缩 API。\n *\n * Compatibility layer for Java users or those who prefer a Builder pattern / Callback based API.\n *\n * This class wraps the coroutine-based [Luban] API.\n */\nclass LubanCompat private constructor(builder: Builder) {\n    private val context: Context? = builder.context\n    private val targetDir: File? = builder.targetDir\n    private val compressListener: OnCompressListener? = builder.compressListener\n    private val inputs: List<Any> = builder.inputs\n    private val lifecycleOwner: LifecycleOwner? = builder.lifecycleOwner\n    private val job = SupervisorJob()\n    private val scope = CoroutineScope(Dispatchers.Main + job)\n\n    private fun launch(): CompressionTask {\n        if (inputs.isEmpty() || compressListener == null) {\n            return object : CompressionTask { override fun cancel() {} }\n        }\n\n        lifecycleOwner?.lifecycle?.addObserver(object : LifecycleEventObserver {\n            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {\n                if (event == Lifecycle.Event.ON_DESTROY) {\n                    cancel()\n                }\n            }\n        })\n\n        compressListener.onStart()\n\n        scope.launch {\n            for (input in inputs) {\n                if (!isActive) break\n                \n                launch {\n                    try {\n                        val outputDir = targetDir ?: context?.cacheDir ?: throw IllegalArgumentException(\"Target directory or Context must be provided\")\n                        \n                        val compressedFileResult = when (input) {\n                            is String -> {\n                                val file = File(input)\n                                if (file.exists()) {\n                                    Luban.compress(file, outputDir)\n                                } else {\n                                    Result.failure(IllegalArgumentException(\"File not found: $input\"))\n                                }\n                            }\n                            is File -> Luban.compress(input, outputDir)\n                            is Uri -> {\n                                if (context != null) {\n                                    Luban.compress(context, input, outputDir)\n                                } else {\n                                    Result.failure(IllegalArgumentException(\"Context required for Uri compression\"))\n                                }\n                            }\n                            else -> Result.failure(IllegalArgumentException(\"Unsupported input type\"))\n                        }\n                        \n                        val result = compressedFileResult.getOrThrow()\n                        if (isActive) {\n                            compressListener.onSuccess(result)\n                        }\n                    } catch (e: Throwable) {\n                        if (isActive) {\n                            compressListener.onError(e)\n                        }\n                    }\n                }\n            }\n        }\n\n        return object : CompressionTask {\n            override fun cancel() {\n                this@LubanCompat.cancel()\n            }\n        }\n    }\n\n    private fun cancel() {\n        job.cancel()\n    }\n    \n    private val isActive: Boolean\n        get() = job.isActive\n\n    /**\n     * 用于构建压缩请求的 Builder。\n     *\n     * Builder for constructing a compression request.\n     *\n     * @param context Android 上下文。\n     * The Android Context.\n     */\n    class Builder(internal val context: Context?) {\n        internal var targetDir: File? = null\n        internal var compressListener: OnCompressListener? = null\n        internal val inputs: MutableList<Any> = mutableListOf()\n        internal var lifecycleOwner: LifecycleOwner? = null\n\n        /**\n         * 向压缩任务中添加单个文件。\n         *\n         * Adds a file to the compression list.\n         *\n         * @param file 需要压缩的图片文件。\n         * The image file to compress.\n         */\n        fun load(file: File): Builder {\n            inputs.add(file)\n            return this\n        }\n\n        /**\n         * 向压缩任务中添加文件路径。\n         *\n         * Adds a file path to the compression list.\n         *\n         * @param path 图片文件的路径。\n         * The path to the image file.\n         */\n        fun load(path: String): Builder {\n            inputs.add(path)\n            return this\n        }\n\n        /**\n         * 向压缩任务中添加图片的 Uri。\n         *\n         * Adds a Uri to the compression list.\n         *\n         * @param uri 图片的 Uri。\n         * The image Uri.\n         */\n        fun load(uri: Uri): Builder {\n            inputs.add(uri)\n            return this\n        }\n        \n        /**\n         * 批量添加待压缩的图片（支持 File、路径字符串或 Uri）。\n         *\n         * Adds a list of items (File, String path, or Uri) to the compression list.\n         *\n         * @param list 待压缩图片的列表。\n         * List of images to compress.\n         */\n        fun <T> load(list: List<T>): Builder {\n            for (item in list) {\n                when (item) {\n                    is String -> load(item)\n                    is File -> load(item)\n                    is Uri -> load(item)\n                }\n            }\n            return this\n        }\n\n        /**\n         * 设置压缩结果输出目录（通过路径字符串）。\n         *\n         * Sets the target directory for compressed images.\n         *\n         * @param targetDir 目标目录路径。\n         * The directory path.\n         */\n        fun setTargetDir(targetDir: String): Builder {\n            this.targetDir = File(targetDir)\n            return this\n        }\n        \n        /**\n         * 设置压缩结果输出目录（通过目录 File 对象）。\n         *\n         * Sets the target directory for compressed images.\n         *\n         * @param targetDir 目标目录 File。\n         * The directory file.\n         */\n        fun setTargetDir(targetDir: File): Builder {\n            this.targetDir = targetDir\n            return this\n        }\n\n        /**\n         * 设置压缩过程的回调监听器。\n         *\n         * Sets the listener for compression events.\n         *\n         * @param listener 压缩回调监听器。\n         * The callback listener.\n         */\n        fun setCompressListener(listener: OnCompressListener): Builder {\n            this.compressListener = listener\n            return this\n        }\n\n        /**\n         * 将压缩任务绑定到指定的 LifecycleOwner，生命周期销毁时会自动取消任务。\n         *\n         * Binds the compression task to a LifecycleOwner.\n         * The task will be automatically cancelled when the lifecycle is destroyed.\n         *\n         * @param lifecycleOwner 生命周期拥有者（例如 Activity 或 Fragment）。\n         * The lifecycle owner (e.g., Activity or Fragment).\n         */\n        fun bindLifecycle(lifecycleOwner: LifecycleOwner): Builder {\n            this.lifecycleOwner = lifecycleOwner\n            return this\n        }\n\n        /**\n         * 启动压缩任务。\n         * \n         * Starts the compression task.\n         * \n         * @return 可用于取消操作的 [CompressionTask]。\n         * A [CompressionTask] that can be used to cancel the operation.\n         */\n        fun launch(): CompressionTask {\n            return LubanCompat(this).launch()\n        }\n    }\n    \n    companion object {\n        /**\n         * 创建一个新的 Builder 实例。\n         *\n         * Creates a new Builder instance.\n         *\n         * @param context Android 上下文。\n         * The Android Context.\n         */\n        @JvmStatic\n        fun with(context: Context): Builder {\n            return Builder(context)\n        }\n    }\n}\n"
  },
  {
    "path": "luban/src/main/java/top/zibin/luban/api/OnCompressListener.kt",
    "content": "package top.zibin.luban.api\n\nimport java.io.File\n\ninterface OnCompressListener {\n    fun onStart()\n    fun onSuccess(file: File)\n    fun onError(e: Throwable)\n}\n"
  },
  {
    "path": "luban/src/main/java/top/zibin/luban/compression/Compressor.kt",
    "content": "package top.zibin.luban.compression\n\nimport android.graphics.Bitmap\n\ninterface Compressor {\n    fun compress(bitmap: Bitmap, targetSizeKb: Int?, fixedQuality: Int? = null): ByteArray\n}\n"
  },
  {
    "path": "luban/src/main/java/top/zibin/luban/compression/JpegCompressor.kt",
    "content": "package top.zibin.luban.compression\n\nimport android.graphics.Bitmap\n\nclass JpegCompressor : Compressor {\n    override fun compress(bitmap: Bitmap, targetSizeKb: Int?, fixedQuality: Int?): ByteArray {\n        val rgbData = bitmapToRgb(bitmap)\n        \n        if (fixedQuality != null) {\n            return TurboJpegNative.compressOrThrow(rgbData, bitmap.width, bitmap.height, fixedQuality)\n        }\n\n        if (targetSizeKb == null) {\n            return TurboJpegNative.compressOrThrow(rgbData, bitmap.width, bitmap.height, 60)\n        }\n\n        val low = 5\n        val high = 95\n        var bestData: ByteArray? = null\n\n        val testResult = TurboJpegNative.compressOrThrow(rgbData, bitmap.width, bitmap.height, 95)\n        val sizeKb = testResult.size / 1024.0\n\n        if (sizeKb <= targetSizeKb) {\n            return testResult\n        }\n\n        var currentLow = low\n        var currentHigh = high\n\n        while (currentLow <= currentHigh) {\n            val mid = (currentLow + currentHigh) / 2\n\n            val compressed = TurboJpegNative.compressOrThrow(rgbData, bitmap.width, bitmap.height, mid)\n            val currentSizeKb = compressed.size / 1024.0\n\n            if (currentSizeKb <= targetSizeKb) {\n                bestData = compressed\n                currentLow = mid + 1\n            } else {\n                currentHigh = mid - 1\n            }\n        }\n\n        if (bestData == null) {\n            bestData = TurboJpegNative.compressOrThrow(rgbData, bitmap.width, bitmap.height, 5)\n        }\n\n        return bestData\n    }\n\n    private fun bitmapToRgb(bitmap: Bitmap): ByteArray {\n        val width = bitmap.width\n        val height = bitmap.height\n        val pixels = IntArray(width * height)\n        bitmap.getPixels(pixels, 0, width, 0, 0, width, height)\n\n        val rgbData = ByteArray(width * height * 3)\n        var offset = 0\n\n        for (pixel in pixels) {\n            rgbData[offset++] = ((pixel shr 16) and 0xFF).toByte()\n            rgbData[offset++] = ((pixel shr 8) and 0xFF).toByte()\n            rgbData[offset++] = (pixel and 0xFF).toByte()\n        }\n\n        return rgbData\n    }\n}\n"
  },
  {
    "path": "luban/src/main/java/top/zibin/luban/compression/TurboJpegNative.kt",
    "content": "package top.zibin.luban.compression\n\nclass CompressionException(message: String, cause: Throwable? = null) : RuntimeException(message, cause)\n\nobject TurboJpegNative {\n    init {\n        System.loadLibrary(\"turbojpeg-wrapper\")\n    }\n\n    @JvmStatic\n    external fun compress(\n        rgbData: ByteArray,\n        width: Int,\n        height: Int,\n        quality: Int\n    ): ByteArray?\n\n    @JvmStatic\n    external fun getErrorString(): String\n\n    fun compressOrThrow(\n        rgbData: ByteArray,\n        width: Int,\n        height: Int,\n        quality: Int\n    ): ByteArray {\n        val result = compress(rgbData, width, height, quality)\n        if (result == null) {\n            val errorMessage = getErrorString().takeIf { it.isNotBlank() }\n                ?: \"JPEG compression failed\"\n            throw CompressionException(\n                \"Failed to compress image (${width}x${height}, quality=$quality): $errorMessage\"\n            )\n        }\n        return result\n    }\n}\n\n"
  },
  {
    "path": "luban/src/main/java/top/zibin/luban/io/ImageLoader.kt",
    "content": "package top.zibin.luban.io\n\nimport android.content.Context\nimport android.graphics.Bitmap\nimport android.graphics.BitmapFactory\nimport android.net.Uri\nimport androidx.exifinterface.media.ExifInterface\nimport kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.withContext\nimport java.io.File\nimport java.io.FileInputStream\nimport java.io.InputStream\nimport androidx.core.graphics.scale\n\ndata class ImageData(\n    val bitmap: Bitmap,\n    val fileSizeKb: Float\n)\n\nclass ImageLoader {\n    suspend fun loadFromUri(\n        context: Context,\n        uri: Uri,\n        targetWidth: Int = 0,\n        targetHeight: Int = 0\n    ): ImageData = withContext(Dispatchers.IO) {\n        val fileSizeKb = getFileSizeFromUri(context, uri)\n\n        val bitmap = context.contentResolver.openInputStream(uri)?.use { inputStream ->\n            decodeStream(inputStream, targetWidth, targetHeight) {\n                context.contentResolver.openInputStream(uri)\n            }?.let { originalBitmap ->\n                val rotation = getRotationFromExifUri(context, uri)\n                if (rotation != 0) {\n                    rotateBitmap(originalBitmap, rotation)\n                } else {\n                    originalBitmap\n                }\n            } ?: throw IllegalArgumentException(\"无法解码图片 (Cannot decode image)\")\n        } ?: throw IllegalArgumentException(\"无法打开 URI (Cannot open URI): $uri\")\n\n        ImageData(bitmap, fileSizeKb)\n    }\n\n    suspend fun loadFromFile(file: File, targetWidth: Int = 0, targetHeight: Int = 0): ImageData =\n        withContext(Dispatchers.IO) {\n            if (!file.exists()) {\n                throw IllegalArgumentException(\"文件不存在 (File does not exist): ${file.absolutePath}\")\n            }\n\n            val fileSizeKb = file.length() / 1024.0f\n\n            FileInputStream(file).use { inputStream ->\n                decodeStream(inputStream, targetWidth, targetHeight) {\n                    FileInputStream(file)\n                }?.let { originalBitmap ->\n                    val rotation = getRotationFromExifFile(file)\n                    if (rotation != 0) {\n                        rotateBitmap(originalBitmap, rotation)\n                    } else {\n                        originalBitmap\n                    }\n                } ?: throw IllegalArgumentException(\"无法解码图片 (Cannot decode image)\")\n            }.let { bitmap ->\n                ImageData(bitmap, fileSizeKb)\n            }\n        }\n\n    private fun decodeStream(\n        inputStream: InputStream,\n        targetWidth: Int,\n        targetHeight: Int,\n        openStream: () -> InputStream?\n    ): Bitmap? {\n        val options = BitmapFactory.Options().apply {\n            inJustDecodeBounds = true\n        }\n        BitmapFactory.decodeStream(inputStream, null, options)\n\n        val originalWidth = options.outWidth\n        val originalHeight = options.outHeight\n\n        if (originalWidth <= 0 || originalHeight <= 0) {\n            return null\n        }\n\n        val maxDimension = 8192\n        val maxMemoryDimension = if (targetWidth > 0 && targetHeight > 0) {\n            maxOf(targetWidth, targetHeight)\n        } else {\n            maxDimension\n        }\n\n        val finalWidth = if (targetWidth > 0) targetWidth else maxMemoryDimension\n        val finalHeight = if (targetHeight > 0) targetHeight else maxMemoryDimension\n\n        options.inSampleSize = calculateInSampleSize(options, finalWidth, finalHeight)\n        options.inJustDecodeBounds = false\n        options.inPreferredConfig = Bitmap.Config.RGB_565\n        options.inScaled = false\n\n        return openStream()?.use { newStream ->\n            var bitmap = BitmapFactory.decodeStream(newStream, null, options)\n\n            if (bitmap != null && (bitmap.width > finalWidth || bitmap.height > finalHeight)) {\n                val scaledBitmap = bitmap.scale(finalWidth, finalHeight)\n                if (scaledBitmap != bitmap) {\n                    bitmap.recycle()\n                    bitmap = scaledBitmap\n                }\n            }\n\n            bitmap\n        }\n    }\n\n    private fun calculateInSampleSize(\n        options: BitmapFactory.Options,\n        reqWidth: Int,\n        reqHeight: Int\n    ): Int {\n        val (height: Int, width: Int) = options.run { outHeight to outWidth }\n        var inSampleSize = 1\n\n        if (height > reqHeight || width > reqWidth) {\n            val halfHeight: Int = height / 2\n            val halfWidth: Int = width / 2\n\n            while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {\n                inSampleSize *= 2\n            }\n        }\n\n        val pixelCount = (width.toLong() * height) / (inSampleSize * inSampleSize)\n        val maxPixels = 16_000_000L\n\n        if (pixelCount > maxPixels) {\n            val scale = kotlin.math.sqrt(pixelCount.toDouble() / maxPixels.toDouble())\n            inSampleSize = (inSampleSize * scale).toInt().coerceAtLeast(1)\n        }\n\n        return inSampleSize\n    }\n\n    private fun getFileSizeFromUri(context: Context, uri: Uri): Float {\n        return try {\n            context.contentResolver.openFileDescriptor(uri, \"r\")?.use { pfd ->\n                pfd.statSize / 1024.0f\n            } ?: 0f\n        } catch (_: Exception) {\n            0f\n        }\n    }\n\n    private fun getRotationFromExifFile(file: File): Int {\n        return try {\n            val exif = ExifInterface(file)\n            getRotationFromExif(exif)\n        } catch (_: Exception) {\n            0\n        }\n    }\n\n    private fun getRotationFromExifUri(context: Context, uri: Uri): Int {\n        return try {\n            context.contentResolver.openInputStream(uri)?.use { inputStream ->\n                val exif = ExifInterface(inputStream)\n                getRotationFromExif(exif)\n            } ?: 0\n        } catch (_: Exception) {\n            0\n        }\n    }\n\n    private fun getRotationFromExif(exif: ExifInterface): Int {\n        return when (exif.getAttributeInt(\n            ExifInterface.TAG_ORIENTATION,\n            ExifInterface.ORIENTATION_NORMAL\n        )) {\n            ExifInterface.ORIENTATION_ROTATE_90 -> 90\n            ExifInterface.ORIENTATION_ROTATE_180 -> 180\n            ExifInterface.ORIENTATION_ROTATE_270 -> 270\n            else -> 0\n        }\n    }\n\n    private fun rotateBitmap(bitmap: Bitmap, degrees: Int): Bitmap {\n        if (degrees == 0) return bitmap\n\n        val matrix = android.graphics.Matrix().apply {\n            postRotate(degrees.toFloat())\n        }\n\n        val rotatedBitmap = Bitmap.createBitmap(\n            bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true\n        )\n\n        if (rotatedBitmap != bitmap) {\n            bitmap.recycle()\n        }\n\n        return rotatedBitmap\n    }\n}\n"
  },
  {
    "path": "luban/src/test/java/top/zibin/luban/CompressionCalculatorTest.kt",
    "content": "package top.zibin.luban\n\nimport org.junit.Assert.assertEquals\nimport org.junit.Assert.assertTrue\nimport org.junit.Test\nimport top.zibin.luban.algorithm.CompressionCalculator\n\nclass CompressionCalculatorTest {\n\n    private val calculator = CompressionCalculator()\n\n    @Test\n    fun `calculateTarget returns correct dimensions for standard large images`() {\n        val width = 1920\n        val height = 1080\n        val target = calculator.calculateTarget(width, height)\n\n        assertTrue(target.width <= width)\n        assertTrue(target.height <= height)\n        assertEquals(0, target.width % 2)\n        assertEquals(0, target.height % 2)\n    }\n\n    @Test\n    fun `calculateTarget handles small images correctly`() {\n        val width = 100\n        val height = 100\n        val target = calculator.calculateTarget(width, height)\n\n        assertEquals(width, target.width)\n        assertEquals(height, target.height)\n    }\n\n    @Test\n    fun `calculateTarget identifies long images`() {\n        val width = 1000\n        val height = 4000 \n        val target = calculator.calculateTarget(width, height)\n\n        assertTrue(\"Should be identified as long image\", target.isLongImage)\n    }\n\n    @Test\n    fun `calculateTarget handles zero or negative dimensions gracefully`() {\n        val target = calculator.calculateTarget(0, 0)\n        assertEquals(0, target.width)\n        assertEquals(0, target.height)\n\n        val targetNegative = calculator.calculateTarget(-100, 100)\n        assertEquals(0, targetNegative.width)\n        assertEquals(0, targetNegative.height)\n    }\n    \n    @Test\n    fun `calculateTarget respects even dimensions constraint`() {\n        val width = 1333\n        val height = 750\n        val target = calculator.calculateTarget(width, height)\n        \n        assertEquals(0, target.width % 2)\n        assertEquals(0, target.height % 2)\n    }\n}\n"
  },
  {
    "path": "luban/src/test/java/top/zibin/luban/ExampleUnitTest.kt",
    "content": "package top.zibin.luban\n\nimport org.junit.Test\n\nimport org.junit.Assert.*\n\n/**\n * 示例本地单元测试，将在开发机器（宿主环境）上运行。\n *\n * 参见 [测试文档](http://d.android.com/tools/testing)。\n *\n * Example local unit test, which will execute on the development machine (host).\n *\n * See [testing documentation](http://d.android.com/tools/testing).\n */\nclass ExampleUnitTest {\n    @Test\n    fun addition_isCorrect() {\n        assertEquals(4, 2 + 2)\n    }\n}"
  },
  {
    "path": "settings.gradle.kts",
    "content": "pluginManagement {\n    repositories {\n        google {\n            content {\n                includeGroupByRegex(\"com\\\\.android.*\")\n                includeGroupByRegex(\"com\\\\.google.*\")\n                includeGroupByRegex(\"androidx.*\")\n            }\n        }\n        mavenCentral()\n        gradlePluginPortal()\n    }\n}\ndependencyResolutionManagement {\n    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)\n    repositories {\n        google()\n        mavenCentral()\n    }\n}\n\nrootProject.name = \"Luban\"\ninclude(\":app\")\ninclude(\":luban\")\ninclude(\":app-java\")\n"
  }
]