简单的java应用程序的问题,从一个图像中删除背景并将其覆盖到另一张图像上并下载处理后的图像

问题描述 投票:0回答:1

本质上我想要创建的是一个简单的Java应用程序,当上传图像时,它会从背景中删除黑色并使其透明,然后存储该图像。然后,来自该 URL“https://pasteboard.co/VA1RxuEWqS4u.jpg”的图像被用作背景图像,JavaScript 将已删除背景的图像覆盖到粘贴板上,并自动下载最终结果。当我运行这个时,没有任何反应,任何帮助将不胜感激。

这是代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Background Remover and Overlay</title>
<style>
  #upload-btn {
    width: 100px;
    height: 40px;
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
  }
</style>
</head>
<body>
<input type="file" id="file-input" style="display: none;">
<button id="upload-btn">Upload Image</button>
<script>
document.getElementById('upload-btn').addEventListener('click', function() {
  document.getElementById('file-input').click();
});

document.getElementById('file-input').addEventListener('change', function(event) {
  const file = event.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = function(e) {
    const img = new Image();
    img.onload = function() {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.width = img.width;
      canvas.height = img.height;
      
      // Draw the image on the canvas
      ctx.drawImage(img, 0, 0);
      
      // Get the image data
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const data = imageData.data;

      // Remove black background (set alpha to 0 for black pixels)
      for (let i = 0; i < data.length; i += 4) {
        const r = data[i];
        const g = data[i + 1];
        const b = data[i + 2];
        // Check if the pixel is black (you can adjust the threshold as needed)
        if (r < 30 && g < 30 && b < 30) {
          data[i + 3] = 0; // Set alpha to 0
        }
      }
      
      // Put the modified image data back onto the canvas
      ctx.putImageData(imageData, 0, 0);

      // Convert canvas to image and download
      const transparentImageUrl = canvas.toDataURL('image/png');
      
      // Load the overlay image from the hosting website
      const overlayImageUrl = 'https://pasteboard.co/VA1RxuEWqS4u.jpg';
      const overlayImg = new Image();
      overlayImg.crossOrigin = 'anonymous';
      overlayImg.onload = function() {
        // Draw the overlay image on the canvas
        ctx.drawImage(overlayImg, 0, 0, canvas.width, canvas.height);
        
        // Convert canvas to image and download the final image
        const finalImageUrl = canvas.toDataURL('image/png');
        const downloadLink = document.createElement('a');
        downloadLink.href = finalImageUrl;
        downloadLink.download = 'final_image.png';
        downloadLink.click();
      };
      overlayImg.src = overlayImageUrl;
    };
    img.src = e.target.result;
  };
  reader.readAsDataURL(file);
});
</script>
</body>
</html>


javascript java html image background
1个回答
0
投票

您的代码因以下几个原因而失败:

  1. 您正在在要戳孔的图像上绘制应该是背景图像的内容(即使黑色像素透明)。应该是相反的 - 远程图像应该首先出现,然后在它上面,删除黑色像素的上传图像。

  2. 另一个问题是您正在尝试加载不是图像的远程资源(尽管有 JPG 扩展名)。您实际上需要使用 this (通过右键单击从原始链接加载的图像获得)。

  3. 第三个问题可能是CORS,特别是如果您在本地测试代码(您的计算机,没有运行本地服务器等)。您可以使用浏览器扩展来克服这个问题(我使用了CORS Everywhere - 我与制作它的人没有任何关系,我只是需要一些东西来调试您的代码,并且我决定这样做)。

解决这些问题的一种方法是对代码进行以下修改。

// the true image URL - perhaps it's better to provide an input
// and let the user set their own URL
// then you'd also have some sort of error handling if the URL
// is not that of an image
const overlayImageUrl = 'https://gcdnb.pbrd.co/images/VA1RxuEWqS4u.jpg';

document.getElementById('file-input').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = function(e) {
        const img = new Image();
        img.onload = function() {
            // this was done so that its meaning
            // it's easily recognizable later on
            const frameWidth = img.width;
            const frameHeight = img.height;

            // the top layer - from the locally loaded image
            const topLayer = document.createElement('canvas');
            const topCtx = topLayer.getContext('2d');
            topLayer.width = frameWidth;
            topLayer.height = frameHeight;

            // draw the top layer
            topCtx.drawImage(img, 0, 0);
            // Get the image data
            const imageData = topCtx.getImageData(0, 0, frameWidth, frameHeight);
            const data = imageData.data;
            // Remove black background (set alpha to 0 for black pixels)
            for (let i = 0; i < data.length; i += 4) {
                const r = data[i];
                const g = data[i + 1];
                const b = data[i + 2];
                // Check if the pixel is black (you can adjust the threshold as needed)
                if (r < 30 && g < 30 && b < 30) {
                    data[i + 3] = 0; // Set alpha to 0
                }
            }

            // Put the modified image data back onto the canvas
            topCtx.putImageData(imageData, 0, 0);

            // Load the overlay image from the hosting website
            const overlayImg = new Image();
            overlayImg.crossOrigin = 'anonymous';
            overlayImg.src = overlayImageUrl;
            overlayImg.onload = function() {
                // the background layer - from the remotely loaded image
                // it's using its own canvas
                const bgLayer = document.createElement('canvas');
                bgLayer.width = img.width;
                bgLayer.height = img.height;
                const bgCtx = bgLayer.getContext('2d');
                bgCtx.drawImage(overlayImg, 0, 0, frameWidth, frameHeight);

                // the composite - here to host the background
                // and the top layer (the one we poked holes in)
                const compositeCanvas = document.createElement('canvas');
                compositeCanvas.width = frameWidth;
                compositeCanvas.height = frameHeight;
                const composite = compositeCanvas.getContext('2d');

                // first the background...
                composite.drawImage(bgLayer,0,0);
                // ... then the top layer - our uploaded image
                composite.drawImage(topLayer,0,0);
                // now the canvas holds two other canvases
                // Convert canvas to image and download the final image
                const finalImageUrl = compositeCanvas.toDataURL('image/png');
                const downloadLink = document.createElement('a');
                downloadLink.href = finalImageUrl;
                downloadLink.download = 'final_image.png';
                downloadLink.click();
            };
        };
        img.src = e.target.result;
    };
    reader.readAsDataURL(file);
});
© www.soinside.com 2019 - 2024. All rights reserved.