SoFunction
Updated on 2025-04-09

Use Java to achieve image mosaic effect

Project Introduction

Mosaic effect is a common image processing technique that simulates the effect of mosaic by dividing the image into multiple small pieces and averaging color for each small piece. This effect is usually used to hide sensitive information in images or add artistic sense to images. In this project, we will use Java's Swing library and image processing technology to achieve mosaic effects of images.

Project Objectives

  • Use the Java Swing library to create a window that displays the original image and images with mosaic effects applied.
  • Break the image into chunks and average the color of each chunk to generate a mosaic effect.
  • Adjust the size of the mosaic block to affect the thickness of the mosaic.

Related knowledge

1. Java Swing

Java Swing is a set of GUI toolkits for Java that are used to create graphical user interfaces. In this project, we will useJPanelTo draw the original image and processed image.

2. Image processing

Image processing is a technology that modifies, enhances, analyzes and other operations on images. In this project, we will process the image using chunking operations, replacing the color of each chunk with the average of pixels in that area, thereby generating a mosaic effect.

3. BufferedImage

BufferedImageThe class represents the pixel data of the image through which each pixel value of the image can be accessed. We can usegetRGBMethod to get the color value of each pixel, usingsetRGBMethod to modify the color value of the pixel.

Project implementation ideas

1. Interface design

Design a simple interface that includes:

  • Image display area: Used to display original images and mosaic-processed images.
  • Controls that resize mosaic blocks: Control the size of each small piece and affect the effect of the mosaic.

2. Mosaic logic

  • Load a picture and convert it toBufferedImagetype.
  • Divide the image into several small pieces and calculate the average color value within each small piece.
  • Replace the pixel color of each chunk with the average color of that chunk to simulate the mosaic effect.

3. User interaction

  • The user controls the size of the small pieces through the slider to change the thickness of the mosaic.

Complete code implementation

import .*;
import .*;
import ;
 
public class MosaicEffect extends JPanel {
    private BufferedImage image; // Original picture    private BufferedImage mosaicImage; // Pictures after mosaic    private final int PANEL_WIDTH = 800; // Panel width    private final int PANEL_HEIGHT = 600; // Panel height    private int blockSize = 20; // The size of each mosaic block 
    public MosaicEffect() {
        (new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
        ();
 
        // Load the picture        image = new ImageIcon("").getImage(); // Please replace it with the actual image path        mosaicImage = new BufferedImage((null), (null), BufferedImage.TYPE_INT_ARGB);
 
        // Pictures after creating mosaic        createMosaicImage();
 
        // Add a slider to control the size of the mosaic block        JSlider slider = new JSlider(, 10, 50, blockSize);
        (10, PANEL_HEIGHT - 50, 200, 30);
        (e -> {
            blockSize = ();
            createMosaicImage(); // Update mosaic image            repaint();
        });
        (slider);
    }
 
    // Create mosaic renderings    private void createMosaicImage() {
        int width = (null);
        int height = (null);
        
        // traverse each small piece of the image        for (int y = 0; y < height; y += blockSize) {
            for (int x = 0; x < width; x += blockSize) {
                int blockWidth = (blockSize, width - x);
                int blockHeight = (blockSize, height - y);
 
                // Calculate the average color of the block area                Color avgColor = getAverageColor(x, y, blockWidth, blockHeight);
                fillBlock(x, y, blockWidth, blockHeight, avgColor);
            }
        }
    }
 
    // Get the average color of the specified area    private Color getAverageColor(int startX, int startY, int width, int height) {
        long r = 0, g = 0, b = 0;
        int count = 0;
        
        // traverse each pixel in the area and calculate the average color        for (int y = startY; y < startY + height; y++) {
            for (int x = startX; x < startX + width; x++) {
                if (x < (null) && y < (null)) {
                    Color color = new Color((x, y));
                    r += ();
                    g += ();
                    b += ();
                    count++;
                }
            }
        }
 
        // Calculate the average color        return new Color((int)(r / count), (int)(g / count), (int)(b / count));
    }
 
    // Fill in small pieces in mosaic image    private void fillBlock(int x, int y, int width, int height, Color color) {
        for (int dy = 0; dy < height; dy++) {
            for (int dx = 0; dx < width; dx++) {
                if (x + dx < () && y + dy < ()) {
                    (x + dx, y + dy, ());
                }
            }
        }
    }
 
    // Draw original pictures and mosaic pictures    @Override
    protected void paintComponent(Graphics g) {
        (g);
        (image, 0, 0, PANEL_WIDTH / 2, PANEL_HEIGHT, this);
        (mosaicImage, PANEL_WIDTH / 2, 0, PANEL_WIDTH / 2, PANEL_HEIGHT, this);
    }
 
    // Main method, create a window and display mosaic effect    public static void main(String[] args) {
        JFrame frame = new JFrame("Picture Mosaic Effect");
        MosaicEffect imagePanel = new MosaicEffect();
        (imagePanel);
        ();
        (JFrame.EXIT_ON_CLOSE);
        (true);
    }
}

Code interpretation

  1. MosaicEffectkind: Inherited fromJPanel, used to draw original pictures and mosaic-processed images. Each time the new mosaic image is calculated and repainted.

  2. image: Store the loaded original image, typeBufferedImage, you can replace the image path as needed.

  3. mosaicImage: Stores the mosaic-processed image, and the color of each pixel is the average color of the pixels in the area.

  4. createMosaicImagemethod: By traversing each area of ​​the original image, calculate the average color within the area and draw it into a small piece. The size of each piece is fromblockSizeDecide.

  5. getAverageColormethod: Calculate the average color of pixels in the specified area. By traversing each pixel in the area, accumulate color values ​​and average them.

  6. fillBlockmethod: Fill the calculated average color into the corresponding area of ​​the mosaic image.

  7. paintComponentmethod: Called every time the interface is redrawn, drawing the original picture and the picture after the mosaic. useDraw the image.

  8. mainmethod: Create aJFrameWindow, addMosaicEffectpanel and display window. The window will automatically display the original image and mosaic image.

Project Summary

Through this project, we have successfully achieved the mosaic effect of the picture. The mosaic effect is simulated by dividing the image into a number of small pieces, each of which is determined by the pixel average value of the region. This project shows how to perform image segmentation, color calculations, and how to draw and manipulate images using Java.

The project can be further expanded:

  • Increase the smooth transition effect of the image to make the mosaic image more natural.
  • Allows users to adjust via sliderblockSize, control the thickness of the mosaic in real time.
  • Add more image processing effects to each small piece, such as blur or edge enhancement.

The above is the detailed content of using Java to achieve image mosaic effects. For more information about Java picture mosaics, please pay attention to my other related articles!