Untitled

mail@pastecode.io avatar
unknown
plain_text
10 days ago
2.7 kB
1
Indexable
Never
// controller:        
requestDto.setImageFaceUrl(WebUtils.encodeImageToBase64(WebUtils.urlLinkImage(img_path, img_domain, requestDto.getImageFaceUrl())));
...
 
 public static String urlLinkImage(List<String> domains, String domainTarget, String linkImgDB) {
        if(StringUtils.isEmpty(linkImgDB)){
            LOGGER.info("linkImgDb is empty");
            return null;
        }
        LOGGER.info("set domain target for: {}", linkImgDB);
        String linkImgTarget;
        for(String url : domains) {
            if(linkImgDB.contains(url)) {
                linkImgTarget = linkImgDB.replace(url, domainTarget);
                LOGGER.info("link img target: {}", linkImgTarget);
                return linkImgTarget;
            }
        }
        return linkImgDB;
    }

...
    public static String encodeImageToBase64(String imageUrl) throws IOException {
        if(StringUtils.isEmpty(imageUrl)) return null;
        LOGGER.info("imageUrl {}", imageUrl);
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        int responseCode = connection.getResponseCode();
        if (responseCode != 200) { // Check for successful response
            return null;
        }

        try (InputStream inputStream = connection.getInputStream();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            byte[] imageBytes = outputStream.toByteArray();
            LOGGER.info("Encode image to Base64. Done");
            return Base64.getEncoder().encodeToString(imageBytes);
        }
    }

// frontend:
 <div class="zoom-wrapper">
                                    <div class="zoom-wrap">
                                        <th:block th:if="${requestObject.getImageCardRectoUrl() != null}">
                                            <img th:src="'data:image/jpeg;base64,'+${requestObject.getImageCardRectoUrl()}"
                                                 alt="" class="img-zoom">
                                        </th:block>
                                        <img th:unless="${requestObject.getImageCardRectoUrl() != null}" src="" alt=""
                                             class="img-zoom">
                                    </div>
                                </div>
Leave a Comment