Spring boot 이미지 stream 또는 base64로 넘기기

2024. 12. 5. 19:07Java/Spring Boot

Stream
Spring boot

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/api")
public class ImageController {

    @GetMapping("/image-stream")
    public ResponseEntity<Resource> getImageStream() throws IOException {
        // Path to the image file
        Path imagePath = Paths.get("/path/to/your/image.jpg");
        Resource resource = new UrlResource(imagePath.toUri());

        if (!resource.exists() || !resource.isReadable()) {
            throw new RuntimeException("Image not found");
        }

        // Return the image as a stream
        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_JPEG) // Adjust based on your image type (e.g., IMAGE_PNG)
                .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"image.jpg\"")
                .body(resource);
    }
}

Sencha

Ext.application({
    name: 'ImageApp',

    launch: function () {
        // AJAX request to fetch the image as a binary stream
        Ext.Ajax.request({
            url: '/api/image-stream', // Your Spring Boot endpoint
            method: 'GET',
            responseType: 'arraybuffer', // Important for binary data
            success: function (response) {
                // Convert the binary data to a base64 URL
                const imageBlob = new Blob([response.responseBytes], { type: 'image/jpeg' }); // Adjust MIME type if needed
                const imageUrl = URL.createObjectURL(imageBlob);

                // Display the image using xtype: 'image'
                Ext.create('Ext.container.Viewport', {
                    layout: 'fit',
                    items: [
                        {
                            xtype: 'image',
                            src: imageUrl, // Use the base64 URL
                            alt: 'Streamed Image',
                            style: {
                                width: '100%',
                                height: 'auto'
                            }
                        }
                    ]
                });
            },
            failure: function () {
                Ext.Msg.alert('Error', 'Failed to load the image.');
            }
        });
    }
});

Base64
Spring boot

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class ImageController {

    @GetMapping("/image-base64")
    public ResponseEntity<Map<String, Object>> getImageBase64() throws IOException {
        // Path to the image file
        Path imagePath = Paths.get("/path/to/your/image.jpg");
        Resource resource = new UrlResource(imagePath.toUri());

        if (!resource.exists() || !resource.isReadable()) {
            throw new RuntimeException("Image not found");
        }

        // Use Files.readAllBytes() to read the image into a byte array
        byte[] imageBytes = Files.readAllBytes(imagePath);
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);

        // Prepare the response
        Map<String, Object> response = new HashMap<>();
        response.put("name", "Sample Image");
        response.put("description", "This is an example image in Base64 format.");
        response.put("image", base64Image); // Base64-encoded image data

        return ResponseEntity.ok(response);
    }
}

Sencha

Ext.application({
    name: 'Base64ImageApp',

    launch: function () {
        // AJAX request to fetch the image in Base64 format
        Ext.Ajax.request({
            url: '/api/image-base64', // Your Spring Boot endpoint
            method: 'GET',
            success: function (response) {
                // Parse the response JSON
                const data = Ext.decode(response.responseText);

                // Create the Base64 image URL
                const base64ImageUrl = `data:image/jpeg;base64,${data.image}`; // Adjust MIME type if needed

                // Create a viewport to display the image
                Ext.create('Ext.container.Viewport', {
                    layout: 'vbox',
                    items: [
                        {
                            xtype: 'panel',
                            title: data.name,
                            html: `<p>${data.description}</p>`,
                            padding: 10
                        },
                        {
                            xtype: 'image',
                            src: base64ImageUrl, // Use the Base64 image URL
                            alt: data.name,
                            style: {
                                width: '100%',
                                height: 'auto'
                            }
                        }
                    ]
                });
            },
            failure: function () {
                Ext.Msg.alert('Error', 'Failed to load the image.');
            }
        });
    }
});