You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将从MySQL获取的Java Blob对象保存为本地图片文件?

How to Convert a Base64 Data URI Blob to an Image File on Disk

Got it, let's break this down clearly. The key thing to note here is that your Blob object doesn't contain raw image binary data — instead, it stores a base64-encoded data URI string (like data:image/png;base64,iVBORw0KGgo...). So we need to process that string first before saving it as an image file.

Here's a step-by-step solution with code:

Step 1: Extract the base64 string from the Blob

Since the Blob holds text content, we'll read it as a string instead of using binary streams directly:

Blob imageBlob;
String base64DataUri = null;
while (rs.next()) {
    imageBlob = rs.getBlob("face");
    // Read the Blob content as a string
    try (Reader reader = imageBlob.getCharacterStream()) {
        StringBuilder sb = new StringBuilder();
        char[] buffer = new char[1024];
        int bytesRead;
        while ((bytesRead = reader.read(buffer)) != -1) {
            sb.append(buffer, 0, bytesRead);
        }
        base64DataUri = sb.toString();
    }
}

Step 2: Strip the data URI prefix

We need to remove the data:image/png;base64, part to get just the base64-encoded image data. If your images might use other formats (like JPEG), you can make this logic more flexible, but for your current case:

// Split the URI to isolate the base64 image content
String base64Image = base64DataUri.split(",")[1];

Step 3: Decode the base64 string to raw binary data

Use Java's built-in Base64 class to convert the base64 string back into the original image byte array:

byte[] imageBytes = Base64.getDecoder().decode(base64Image);

Step 4: Write the byte array to a disk file

Use FileOutputStream (with try-with-resources to auto-close the stream) to save the binary data as an image file:

// Replace with your desired file path and name
String outputPath = "/your/target/path/image.png";
try (FileOutputStream fos = new FileOutputStream(outputPath)) {
    fos.write(imageBytes);
    System.out.println("Image saved successfully to " + outputPath);
}

Full Complete Code (with error handling)

Here's the combined code with proper exception handling and resource management:

import java.sql.Blob;
import java.sql.ResultSet;
import java.io.*;
import java.util.Base64;

// ... your existing database connection/query code ...

Blob imageBlob;
String base64DataUri = null;

try {
    while (rs.next()) {
        imageBlob = rs.getBlob("face");
        // Read Blob content as a string
        try (Reader reader = imageBlob.getCharacterStream()) {
            StringBuilder sb = new StringBuilder();
            char[] buffer = new char[1024];
            int bytesRead;
            while ((bytesRead = reader.read(buffer)) != -1) {
                sb.append(buffer, 0, bytesRead);
            }
            base64DataUri = sb.toString();
        }
    }

    if (base64DataUri != null && base64DataUri.contains(",")) {
        String base64Image = base64DataUri.split(",")[1];
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);
        
        // Save to disk
        String outputFile = "output_image.png";
        try (FileOutputStream fos = new FileOutputStream(outputFile)) {
            fos.write(imageBytes);
            System.out.println("Image saved to: " + new File(outputFile).getAbsolutePath());
        } catch (IOException e) {
            System.err.println("Failed to write image file: " + e.getMessage());
            e.printStackTrace();
        }
    } else {
        System.err.println("Invalid base64 data URI format in Blob");
    }
} catch (Exception e) {
    System.err.println("Error processing Blob data: " + e.getMessage());
    e.printStackTrace();
}

Key Notes:

  • Why not use getBinaryStream()? Because your Blob contains a text-based data URI, not raw image bytes. Reading it as a binary stream would give you the bytes of the string itself, not the actual image data.
  • Support for other image formats: If your database might store different image types (JPEG, GIF), you can parse the MIME type from the data URI (the part between data: and ;base64) to set the correct file extension dynamically.

内容的提问来源于stack exchange,提问作者Deyan koba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:03:25