Untitled

mail@pastecode.io avatar
unknown
plain_text
9 days ago
2.0 kB
0
Indexable
Never
  const processImage = () => {
    if (!originalImage) {
      setError("Please upload an image first.");
      return;
    }

    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');

    // Set canvas size to match original image
    canvas.width = originalImage.width;
    canvas.height = originalImage.height;

    // Draw original image
    ctx.drawImage(originalImage, 0, 0);

    // Get image data
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    const data = imageData.data;

    // Calculate dimensions for downscaled image
    const pixelSize = Math.ceil(1 / scaleFactor);
    const scaledWidth = Math.floor(canvas.width / pixelSize);
    const scaledHeight = Math.floor(canvas.height / pixelSize);

    // Create a temporary canvas for the downscaled image
    const tempCanvas = document.createElement('canvas');
    tempCanvas.width = scaledWidth;
    tempCanvas.height = scaledHeight;
    const tempCtx = tempCanvas.getContext('2d');
    tempCtx.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight);

    // Get the downscaled image data
    const scaledImageData = tempCtx.getImageData(0, 0, scaledWidth, scaledHeight);
    const scaledData = scaledImageData.data;

    // Process the image with large pixel effect
    for (let y = 0; y < canvas.height; y++) {
      for (let x = 0; x < canvas.width; x++) {
        const srcX = Math.floor(x / pixelSize);
        const srcY = Math.floor(y / pixelSize);
        const srcIndex = (srcY * scaledWidth + srcX) * 4;
        const destIndex = (y * canvas.width + x) * 4;

        data[destIndex] = scaledData[srcIndex];
        data[destIndex + 1] = scaledData[srcIndex + 1];
        data[destIndex + 2] = scaledData[srcIndex + 2];
        data[destIndex + 3] = scaledData[srcIndex + 3];
      }
    }

    // Put the processed image data back on the canvas
    ctx.putImageData(imageData, 0, 0);

    // Set processed image
    setProcessedImage(canvas.toDataURL());
  };
Leave a Comment