Skip to content

feat(core): Add watermark 实现 #2122

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 2, 2025
Merged

feat(core): Add watermark 实现 #2122

merged 1 commit into from
May 2, 2025

Conversation

unknowIfGuestInDream
Copy link
Owner

@unknowIfGuestInDream unknowIfGuestInDream commented May 2, 2025

Close: #1927

Fixes #

Proposed Changes

  1. ...
  2. ...
  3. ...

Readiness Checklist

Author/Contributor

  • If documentation is needed for this change, has that been included in this pull request

Reviewing Maintainer

  • Label as either enhancement, bug, documentation or dependencies
  • Verify design and implementation

Summary by Sourcery

Implement a Least Significant Bit (LSB) watermarking technique for images, allowing embedding and extraction of invisible text watermarks

New Features:

  • Add LSB watermarking implementation for embedding and extracting text watermarks in images

Tests:

  • Add parameterized test for LSB watermarking with different image types

Chores:

  • Add copyright headers to new files

Summary by CodeRabbit

  • 新功能
    • 新增基于LSB(最低有效位)的不可见图片水印功能,支持在PNG图片中嵌入和提取文本水印。
  • 测试
    • 增加了针对LSB不可见水印功能的自动化测试,验证PNG和JPEG图片的水印嵌入与提取效果。

Close: #1927
Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
Copy link

Thank you for following naming conventions! 😻

Copy link

vercel bot commented May 2, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
javafx-tool ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 2, 2025 6:24am

Copy link

sourcery-ai bot commented May 2, 2025

Reviewer's Guide

This pull request introduces an image watermarking feature using the Least Significant Bit (LSB) technique. It adds a new LSBWatermark class that embeds textual watermarks into images by modifying the LSB of pixel color channels and provides functionality to extract them. Unit tests are included to verify the implementation, noting limitations with lossy image formats.

File-Level Changes

Change Details Files
Implemented LSB watermarking logic.
  • Added addTextWatermark method to embed watermark text length (first 16 bits) and data into image pixel LSBs.
  • Added extractTextWatermark method to read watermark length and data from image pixel LSBs.
  • Included helper methods to set and get individual bits from pixel color channels (RGB).
core/src/main/java/com/tlcsdm/core/watermark/LSBWatermark.java
Added unit tests for LSB watermarking.
  • Created parameterized tests to verify adding and extracting watermarks for different image types (PNG, JPG).
  • Included assertions to check the correctness of extracted watermarks, acknowledging potential issues with lossy formats like JPG.
core/src/test/java/com/tlcsdm/core/watermark/InvisibleWatermarkTest.java

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

quine-bot bot commented May 2, 2025

👋 Figuring out if a PR is useful is hard, hopefully this will help.

  • @unknowIfGuestInDream has been on GitHub since 2019 and in that time has had 1220 public PRs merged
  • Don't you recognize them? They've been here before 🎉
  • Here's a good example of their work: javafxTool (Javafx scaffolding, built on JDK17 + JavaFX21 + controlsfx 11.x.x + Maven)
  • From looking at their profile, they seem to be good with Java and HTML.

Their most recently public accepted PR is: #2118

Copy link

coderabbitai bot commented May 2, 2025

Walkthrough

本次变更新增了一个基于最不重要位(LSB)的图片隐形水印功能,包括水印的嵌入与提取。核心实现为新建的 LSBWatermark 类,提供了向 PNG 图片嵌入文本水印和从图片中提取水印的静态方法。同时,新增了 InvisibleWatermarkTest 测试类,通过参数化测试验证了水印功能在 PNG 和 JPEG 图片上的表现。测试确保 PNG 图片可正确嵌入与提取水印,而 JPEG 图片由于格式原因无法准确提取。

Changes

文件/分组 变更摘要
core/src/main/java/com/tlcsdm/core/watermark/LSBWatermark.java 新增 LSBWatermark 类,实现基于LSB的图片隐形水印添加与提取方法。
core/src/test/java/com/tlcsdm/core/watermark/InvisibleWatermarkTest.java 新增 InvisibleWatermarkTest 测试类,参数化测试水印功能。

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant LSBWatermark
    participant ImageFile

    User->>LSBWatermark: addTextWatermark(inputImage, outputImage, watermarkText)
    LSBWatermark->>ImageFile: 读取 inputImage
    LSBWatermark->>LSBWatermark: 编码 watermarkText 为 bit 序列
    LSBWatermark->>ImageFile: 修改像素LSB嵌入水印
    LSBWatermark->>ImageFile: 写入 outputImage

    User->>LSBWatermark: extractTextWatermark(watermarkedImage)
    LSBWatermark->>ImageFile: 读取 watermarkedImage
    LSBWatermark->>LSBWatermark: 提取LSB重构水印文本
    LSBWatermark-->>User: 返回水印文本
Loading

Assessment against linked issues

Objective Addressed Explanation
实现图片隐形水印的嵌入与提取功能(#1927

Poem

🐇
水印悄悄藏像素,
PNG中秘密留。
兔子跳跃代码间,
隐形文字不外流。
测试通过心欢喜,
2025著作权,
只在图片深处游!

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@mergify mergify bot added the enhancement New feature or request label May 2, 2025
Copy link

sonarqubecloud bot commented May 2, 2025

Quality Gate Passed Quality Gate passed

Issues
0 New issues
0 Accepted issues

Measures
0 Security Hotspots
No data about Coverage
0.0% Duplication on New Code

See analysis details on SonarQube Cloud

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @unknowIfGuestInDream - I've reviewed your changes - here's some feedback:

  • Consider updating the PR title to use consistent language (e.g., English only).
  • Please fill out the 'Proposed Changes' section in the description to summarize the key modifications.
Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🟢 Security: all looks good
  • 🟡 Testing: 3 issues found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (8)
core/src/main/java/com/tlcsdm/core/watermark/LSBWatermark.java (6)

37-48: 类文档完善建议

类文档说明了LSB水印的局限性,但建议进一步完善:

  1. 增加对嵌入容量的说明(每个像素可存储3位,即RGB各1位)
  2. 明确指出只支持PNG格式的原因(JPEG有损压缩会破坏LSB信息)
  3. 建议添加对使用场景的具体示例

67-68: 计算公式说明不足

计算所需像素数的公式 (watermarkBytes.length * 8 + 2) / 3 中的 + 2 部分目的不明确。建议添加注释说明此计算逻辑,或者修改为更清晰的表达方式。


78-82: 水印长度限制应在文档中说明

当前实现使用16位存储水印长度,这意味着水印最大只能是2^16字节。建议在方法文档中明确说明此限制,以便用户了解适用范围。


150-158: 字节数组长度校正逻辑可优化

当前代码分别处理两种情况:字节数组长度小于或大于预期长度。可以简化为单一的条件判断,提高代码可读性。

// 确保字节数组长度正确
-if (watermarkBytes.length < watermarkLength) {
-    byte[] correctedBytes = new byte[watermarkLength];
-    System.arraycopy(watermarkBytes, 0, correctedBytes, 0, watermarkBytes.length);
-    watermarkBytes = correctedBytes;
-} else if (watermarkBytes.length > watermarkLength) {
-    byte[] correctedBytes = new byte[watermarkLength];
-    System.arraycopy(watermarkBytes, 0, correctedBytes, 0, watermarkLength);
-    watermarkBytes = correctedBytes;
+if (watermarkBytes.length != watermarkLength) {
+    byte[] correctedBytes = new byte[watermarkLength];
+    System.arraycopy(watermarkBytes, 0, correctedBytes, 0, Math.min(watermarkBytes.length, watermarkLength));
+    watermarkBytes = correctedBytes;
}

171-176: switch语句中的default分支冗余

由于channel变量被限制为0-2(通过 channel = bitIndex % 3),所以switch语句中的default分支永远不会被执行。建议移除此冗余分支。

// 根据位索引决定读取哪个通道的最低有效位
int channel = bitIndex % 3;
return switch (channel) {
    case 0 -> ((rgb >> 16) & 0x01) == 1;
    case 1 -> ((rgb >> 8) & 0x01) == 1;
    case 2 -> (rgb & 0x01) == 1;
-    default -> false;
};

49-178: 建议添加额外的安全措施和功能增强

当前实现是LSB水印的基础版本,建议考虑以下增强:

  1. 添加加密选项,提高水印安全性
  2. 实现水印扩散机制,使水印更均匀分布在图像中,增加鲁棒性
  3. 提供检测水印是否存在的方法,而不仅仅是提取水印
  4. 增加对图像处理操作(如轻微裁剪、旋转)的抵抗能力

此外,建议将静态方法重构为实例方法,提供更灵活的配置选项。

core/src/test/java/com/tlcsdm/core/watermark/InvisibleWatermarkTest.java (2)

43-68: 建议增加更多的测试场景

当前测试只覆盖了基本功能,建议增加以下测试场景:

  1. 测试图像过小无法容纳水印的情况
  2. 测试不同长度的水印文本
  3. 测试水印提取失败的边界情况
  4. 测试图像处理操作(如剪裁、调整大小)后水印的可提取性
  5. 测试性能边界(大图像、长水印)

54-54: 测试数据可配置化

水印文本直接硬编码在测试方法中。建议将其抽取为常量或通过参数化方式提供,以便更灵活地测试不同长度和内容的水印。

@ParameterizedTest
@ValueSource(strings = {"watermark/originBig.jpg", "watermark/originSmall.png"})
void lsb(String inputImagePath) throws IOException {
+    // 定义为常量或考虑通过参数化方式提供不同长度的水印文本
+    final String WATERMARK_TEXT = "Copyright 2025 - Tlcsdm";
    
    File inputImage = new File(ResourceUtil.getResource(inputImagePath).getFile());
    File parentFile = inputImage.getParentFile();
    // 添加暗水印
    File watermarkedImage = new File(parentFile,
        FilenameUtils.getBaseName(inputImage.getName()) + "_lsb." + FilenameUtils.getExtension(
            inputImage.getName()));
-    String watermarkText = "Copyright 2025 - Tlcsdm";

-    LSBWatermark.addTextWatermark(inputImage, watermarkedImage, watermarkText);
+    LSBWatermark.addTextWatermark(inputImage, watermarkedImage, WATERMARK_TEXT);
    StaticLog.info("暗水印添加成功!");

    // 提取暗水印
    String extractedWatermark = LSBWatermark.extractTextWatermark(watermarkedImage);
    if ("png".equals(FilenameUtils.getExtension(inputImage.getName()))) {
-        Assertions.assertEquals(watermarkText, extractedWatermark);
+        Assertions.assertEquals(WATERMARK_TEXT, extractedWatermark);
    } else {
-        Assertions.assertNotEquals(watermarkText, extractedWatermark);
+        Assertions.assertNotEquals(WATERMARK_TEXT, extractedWatermark);
    }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a6beb09 and d2e8ffe.

⛔ Files ignored due to path filters (2)
  • core/src/test/resources/watermark/originBig.jpg is excluded by !**/*.jpg
  • core/src/test/resources/watermark/originSmall.png is excluded by !**/*.png
📒 Files selected for processing (2)
  • core/src/main/java/com/tlcsdm/core/watermark/LSBWatermark.java (1 hunks)
  • core/src/test/java/com/tlcsdm/core/watermark/InvisibleWatermarkTest.java (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
core/src/test/java/com/tlcsdm/core/watermark/InvisibleWatermarkTest.java (1)
core/src/main/java/com/tlcsdm/core/watermark/LSBWatermark.java (1)
  • LSBWatermark (49-178)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: automerge
  • GitHub Check: qodana
  • GitHub Check: build (21, macos-latest, false)
  • GitHub Check: build (21, windows-latest, false)
  • GitHub Check: build (17, windows-latest, false)
  • GitHub Check: build (21, ubuntu-latest, false)
  • GitHub Check: build (17, macos-latest, false)
  • GitHub Check: build (17, ubuntu-latest, false)
  • GitHub Check: StepSecurity Harden-Runner
  • GitHub Check: Summary
🔇 Additional comments (3)
core/src/main/java/com/tlcsdm/core/watermark/LSBWatermark.java (1)

107-111: 使用了Java 14+的语法特性

此处使用了Java 14+引入的switch表达式箭头语法。确保项目的Java版本兼容性要求支持此特性。

core/src/test/java/com/tlcsdm/core/watermark/InvisibleWatermarkTest.java (2)

45-47: 参数化测试用例命名明确

参数化测试使用@ValueSource提供了不同格式的图片文件进行测试,设计合理。测试数据包含了JPEG和PNG格式,有效验证了不同格式的支持情况。


61-65: 测试断言逻辑清晰明确

测试断言逻辑正确区分了PNG和其他格式的期望结果:PNG格式应能正确提取水印,而其他格式(如JPEG)则无法正确提取。这符合LSB水印的技术特性和类文档中的说明。

Copy link
Contributor

github-actions bot commented May 2, 2025

Qodana Community for JVM

It seems all right 👌

No new problems were found according to the checks applied

💡 Qodana analysis was run in the pull request mode: only the changed files were checked
☁️ View the detailed Qodana report

Contact Qodana team

Contact us at qodana-support@jetbrains.com

GitHub
Explore the GitHub Discussions forum for JetBrains Qodana. Discuss code, ask questions & collaborate with the developer community.

@unknowIfGuestInDream unknowIfGuestInDream merged commit 350d513 into master May 2, 2025
37 checks passed
@unknowIfGuestInDream unknowIfGuestInDream deleted the water branch May 2, 2025 06:42
@quine-bot quine-bot bot mentioned this pull request May 2, 2025
3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature Request] java隐藏水印
1 participant