search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
1. Decode Base64 string
2. Convert byte array to BufferedImage
3. Write BufferedImage to file
Complete sample code
Things to note:
Exception handling:
JSON library:
Image format:
Validity of Base64 string:
Use in Spring
Summarize
Home Java javaTutorial Convert ByteArray in JSON to Image in Java or Spring

Convert ByteArray in JSON to Image in Java or Spring

Dec 04, 2025 am 03:57 AM

Convert ByteArray in JSON to Image in Java or Spring

This article explains how to convert a ByteArray from JSON to an image using Java or Spring. The core idea is to decode the Base64-encoded image data into a byte array, then use the `javax.imageio` package to convert it into a BufferedImage object, and finally write it to a file.

In many web applications, image data is often transmitted in JSON format, where the image itself may be encoded as a Base64 string. To use such image data in a Java or Spring application, it needs to be converted to an image file (for example, JPG or PNG). Here are the steps on how to achieve this:

1. Decode Base64 string

First, the Base64 encoded image data needs to be decoded into a byte array. This can be done using the java.util.Base64 class.

 import java.util.Base64;

String base64Image = jsonData.get("image"); // Get the Base64 string byte[] from JSON imageBytes = Base64.getDecoder().decode(base64Image);

2. Convert byte array to BufferedImage

Next, you need to convert the byte array into a BufferedImage object using the javax.imageio.ImageIO class. First, create a ByteArrayInputStream and then use the ImageIO.read() method to read the image.

 import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;

ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
BufferedImage image = null;
try {
    image = ImageIO.read(bis);
} catch (IOException e) {
    // Handle IO exception e.printStackTrace();
}

3. Write BufferedImage to file

Finally, the BufferedImage can be written to a file using the ImageIO.write() method. Specify the image format (for example, "jpg" or "png") and output file.

 import java.io.File;
import java.io.IOException;

try {
    ImageIO.write(image, "jpg", new File("output.jpg"));
} catch (IOException e) {
    // Handle IO exception e.printStackTrace();
}

Complete sample code

Here is a complete example showing how to convert Base64 encoded image data in JSON to a JPG file:

 import java.util.Base64;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import org.json.JSONObject; // Assume that the org.json library is used to process JSON

public class ImageConverter {

    public static void main(String[] args) {
        // Simulate the JSON data String obtained from the API jsonString = "{ \"id\": \"63044\", \"image\": \"iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAYAAACI7Fo9AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEh ZcwAADsMAAA7DAcdvqGQAACsgSURBVHhe7Z1b7MVpdZY5CDIwwzADM8xw6ABaa9PaUDBGKaapF6YX1ko10tQLFI22mJAQE MxWi88YOMpVqO3Vm3SaGgqJhprbVr1pqGaINB6Qwu9KCUCQjnDdr4/ 51Z88x691rfPnx77P49yRvnPXy/k9mdYWZon7Xb2Nj4Dc/2Q9/YuAG2H/rGxg2w/dA3Nm6A7Ye sXEDbD/0jY0bYPuhb2zcANsPfWPjBth 6BsbN8D2Q9/YuAG2H/rGxg2w/dA3Nm6A7Ye sXEDbD/0jY0bYPuhb2zcANsPfWPjBth 6BsbN8D2Q9/YuAG2H/rGxg2w/dA3Nm6A5T/0Zz3rWUdJuJxwJzmybZRweZfqXLx2tmMvCeeZC5c74r Xiua5nLthLgl64XLCXZy6qnD3zrlaz/I7ZS3ckXE64kxzZNkq4vEt1Ll4727GXhPPMhcsd8VrxXNczF wlQS9cLtjLMxdVzp55V6tZfsfZF VenhL0Im47ItkmilQ5Jbq5RLJNVIXbHZtXclQ79k5dunvuuufE7P5cLL/jqR9GnhL0Im47ItkmilQ5Jbq5RLJNVIXbHZtXclQ79k5dunvuuufE7P5cLL8jX1SeEs5TpJt3d0I5e aSyLohwrzyorsT6iuRKq8knKdE5UW1k3dyuJ3zlKBfxfI7uhenhPMU6ebdnVDOnrkksm6IMK 86O6E kqkyisJ5ylReVHt5J0cbuc8JehXsfyO7sUpQe9w57qqqPYuF/FsVEV2Zkhk3ZDIulMkjvUun6V7n WpXeVLt5SlBv4rld3QvTgl6hzvXVUW1d7mIZ6MqsjN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yguXC/Vu53LBXr7KKVHlovLC 5UQ76tJk94wS9MT1zOVd3sXtlbOv/LW42hPoAziJyguXC/Vu53LBXr7KKVHlovLC5UQ76tJk94wS9MT1zOVd3sXtlbOv/LW42hPoA8x iOqc........................\"; }";

        // Use org.json to parse JSON
        JSONObject jsonObject = new JSONObject(jsonString);
        String base64Image = jsonObject.getString("image");

        // 1. Decode Base64 string byte[] imageBytes = Base64.getDecoder().decode(base64Image);

        // 2. Convert byte array to BufferedImage
        ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
        BufferedImage image = null;
        try {
            image = ImageIO.read(bis);
        } catch (IOException e) {
            System.err.println("Error reading image from byte array: " e.getMessage());
            return; //End program}

        // 3. Write BufferedImage to file if (image != null) {
            try {
                File outputFile = new File("output.jpg");
                ImageIO.write(image, "jpg", outputFile);
                System.out.println("Image saved to: " outputFile.getAbsolutePath());
            } catch (IOException e) {
                System.err.println("Error writing image to file: " e.getMessage());
            }
        } else {
            System.err.println("Could not create BufferedImage from byte array.");
        }
    }
}

Things to note:

  • Exception handling: In real applications, IOException should always be handled because image read and write operations may fail.
  • JSON library: The org.json library is used in the example, you need to add it to the dependencies of your project. If using Spring, consider using libraries such as Jackson or Gson.
  • Image format: Change the image format in the ImageIO.write() method as needed (for example, "png").
  • Validity of Base64 string: Make sure the Base64 string is valid, otherwise the decoding process may fail.

Use in Spring

In a Spring application, this logic can be encapsulated in a Service class and exposed as an API endpoint through a Controller. For example:

 import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Base64;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;

@Service
public class ImageService {

    public String convertBase64ToImage(String base64Image, String fileName) throws IOException {
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);
        ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
        BufferedImage image = ImageIO.read(bis);

        if (image == null) {
            throw new IllegalArgumentException("Invalid Base64 encoded image data");
        }

        File outputFile = new File(fileName ".jpg");
        ImageIO.write(image, "jpg", outputFile);
        return outputFile.getAbsolutePath();
    }
}

Then in the Controller:

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class ImageController {

    @Autowired
    private ImageService imageService;

    @PostMapping("/convert")
    public String convertImage(@RequestParam("base64Image") String base64Image, @RequestParam("fileName") String fileName) {
        try {
            return imageService.convertBase64ToImage(base64Image, fileName);
        } catch (IOException e) {
            return "Error converting image: " e.getMessage();
        }
    }
}

Summarize

This article provides a simple method to convert Base64 encoded image data in JSON to image files in Java or Spring applications. Image data can be easily used in applications by decoding a Base64 string, converting it to a BufferedImage object, and writing it to a file. Remember to always handle exceptions and verify the validity of Base64 strings.

The above is the detailed content of Convert ByteArray in JSON to Image in Java or Spring. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to configure Spark distributed computing environment in Java_Java big data processing How to configure Spark distributed computing environment in Java_Java big data processing Mar 09, 2026 pm 08:45 PM

Spark cannot run in local mode, ClassNotFoundException: org.apache.spark.sql.SparkSession. This is the most common first step of getting stuck: even the dependencies are not correct. Only spark-core_2.12 is written in Maven, but spark-sql_2.12 is not added. SparkSession crashes as soon as it is built. The Scala version must strictly match the official Spark compiled version - Spark3.4.x uses Scala2.12 by default. If you use spark-sqljar of 2.13, the class loader cannot directly find the main class. Practical advice: Go to mvnre

How to safely map user-entered weekday string to integer value and implement date offset operation in Java How to safely map user-entered weekday string to integer value and implement date offset operation in Java Mar 09, 2026 pm 09:43 PM

This article introduces a concise and maintainable way to map the weekday string (such as "Monday") to the corresponding serial number (1-7), and use the modulo operation to realize the forward and backward offset of any number of days (such as Monday plus 4 days to get Friday), avoiding lengthy if chains and hard-coded logic.

How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers Mar 09, 2026 pm 09:48 PM

Homebrew installs the latest stable version of openjdk (such as JDK22) by default, not the LTS version; you need to explicitly execute brewinstallopenjdk@17 or brewinstallopenjdk@21 to install the LTS version, and manually configure PATH and JAVA_HOME to be correctly recognized by the system and IDE.

What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling Mar 10, 2026 pm 06:57 PM

What is SuppressedException: It is not "swallowed", but actively archived by the JVM. SuppressedException is not an exception loss, but the JVM quietly attaches the secondary exception to the main exception under the premise that "only one exception must be thrown" for you to verify afterwards. It is automatically triggered by the JVM in only two scenarios: one is that the resource closure in try-with-resources fails, and the other is that you manually call addSuppressed() in finally. The key difference is: the former is fully automatic and safe; the latter requires you to keep it to yourself, and it can be written as shadowing if you are not careful. try-

How to correctly implement runtime file writing in Java applications (avoiding JAR internal write failures) How to correctly implement runtime file writing in Java applications (avoiding JAR internal write failures) Mar 09, 2026 pm 07:57 PM

After a Java application is packaged as a JAR, data cannot be written directly to the resources in the JAR package (such as test.txt) because the JAR is essentially a read-only ZIP archive; the correct approach is to write variable data to an external path (such as a user directory, a temporary directory, or a configuration-specified path).

What is the underlying principle of array expansion in Java_Java memory dynamic adjustment analysis What is the underlying principle of array expansion in Java_Java memory dynamic adjustment analysis Mar 09, 2026 pm 09:45 PM

ArrayList.add() triggers expansion because grow() is called when size is equal to elementData.length. The first add allocates 10 capacity, and subsequent expansion is 1.5 times and not less than the minimum requirement, relying on delayed initialization and System.arraycopy optimization.

Complete tutorial on reading data from file and initializing two-dimensional array in Java Complete tutorial on reading data from file and initializing two-dimensional array in Java Mar 09, 2026 pm 09:18 PM

This article explains in detail how to load an integer sequence in an external text file into a Java two-dimensional array according to a specified row and column structure (such as 2500×100), avoiding manual assignment or index out-of-bounds, and ensuring accurate data order and robust and reusable code.

A concise method in Java to compare whether four byte values ​​are equal and non-zero A concise method in Java to compare whether four byte values ​​are equal and non-zero Mar 09, 2026 pm 09:40 PM

This article introduces several professional solutions for efficiently and safely comparing multiple byte type return values ​​(such as getPlayer()) in Java to see if they are all equal and non-zero. We recommend two methods, StreamAPI and logical expansion, to avoid Boolean and byte mis-comparison errors.

Related articles