1

I have the following function that should convert a image form an url to a base64encoded inline-Image.

function imageToBase64Jpg($imagePath, $maxWidth=825){
    $imageType = exif_imagetype($imagePath);
    if ($imageType == IMAGETYPE_WEBP) $image = imagecreatefromwebp($imagePath);
    elseif ($imageType == IMAGETYPE_JPEG) $image = imagecreatefromjpeg($imagePath);
    else return '<img src="'.$imagePath.'">';



    if ($image === false) return '<img src="'.$imagePath.'">';
    $originalWidth = imagesx($image);
    if ($originalWidth > $maxWidth) {
        $originalHeight = imagesy($image);
        $newWidth = $maxWidth;
        $newHeight = (int) (($newWidth / $originalWidth) * $originalHeight);
        $image = imagescale($image, $newWidth, $newHeight);
    }

    ob_start();
    imagejpeg($image, null, 80);
    $jpgImage = ob_get_contents();
    ob_end_clean();
    imagedestroy($image);
    // imagejpeg($image,'test.jpg',80);
    return '<img src="data:image/jpeg;base64,' . base64_encode($jpgImage).'" alt="">';
}

But the image is corrupt most of the time . But to me the function seems ok. If I write it directly to the harddisc, the image looks just fine, but the base64-version is full with artefacts. Can anyone see what i am doing wrong?

4
  • 1
    My guess, its most likely the original image that causes issues. Check so they are RGB, and not CMYK. In most cases when it comes to image manipulation, its often better to create a new image, and overlay the image you want to save/render. php.net/manual/en/function.imagejpeg.php The Second comment, 15 year old comment, is still a very good, memory friendly, solution.
    – Anuga
    Commented Dec 2 at 17:28
  • 2
    Where is $image defined? You say the image is corrupt most of the time - under what conditions does it work or not work? You then say it is full of artefacts which is very different from being corrupt. Please clarify. Commented Dec 2 at 21:10
  • 1
    "but the base64-version is full with artefacts" - I'm really not certain what that means. Visual artifacts, like a JPEG compression artifact or something? Or does the base64 code itself look weird? What if you run it through a tool such as dopiaza.org/tools/datauri/index.php, does that also look weird?
    – Chris Haas
    Commented Dec 2 at 21:32
  • It looked like jpeg-compression errors. eg. the last third of the image was darker. Sometimes the whole image had parts with overlayed red blocks. But now it seems that it works fine with the same images without changing the code. Thank you all for your help.
    – E. Reuter
    Commented Dec 4 at 6:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.