简体   繁体   中英

How to convert binary image data to image file and save it in folder in php

I have a program that convert image file to binary and also it converts the binary data to image file . I have done the first, I could convert the image file to binary . But the second one not done yet.

How to convert and save binary data to image file

I am checking this in PHP .Please help me

尝试imagecreatefromstring方法,该方法在此处记录

You can use below code with option of saving an image and resizing saved png image without losing its transparent/white effect :

$data = 'binary data of image';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
// assign new width/height for resize purpose
$newwidth = $newheight = 50;
// Create a new image from the image stream in the string
$thumb = imagecreatetruecolor($newwidth, $newheight); 

if ($im !== false) {

    // Select the HTTP-Header for the selected filetype 
    #header('Content-Type: image/png'); // uncomment this code to display image in browser

    // alter or save the image  
    $fileName = $_SERVER['DOCUMENT_ROOT'].'server location to store image/'.date('ymdhis').'.png'; // path to png image
    imagealphablending($im, false); // setting alpha blending on
    imagesavealpha($im, true); // save alphablending setting (important)

    // Generate image and print it
    $resp = imagepng($im, $fileName);

    // resizing png file
    imagealphablending($thumb, false); // setting alpha blending on
    imagesavealpha($thumb, true); // save alphablending setting (important)

    $source = imagecreatefrompng($fileName); // open image
    imagealphablending($source, true); // setting alpha blending on

    list($width, $height, $type, $attr) = getimagesize($fileName);
    #echo '<br>' . $width . '-' . $height . '-' . $type . '-' . $attr . '<br>';

    imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    $newFilename = $_SERVER['DOCUMENT_ROOT'].'server location to store image/resize_'.date('ymdhis').'.png';
    $resp = imagepng($thumb,$newFilename);

    // frees image from memory
    imagedestroy($im);
    imagedestroy($thumb);

}
else {
    echo 'An error occurred.';
}

Same way, we can do for JPEG, JPG and GIF format of images.

Hope it helps to people here!

You would convert your binary stream (of i assume r/g/b values) back into decimal notation and write the pixel to the image you are creating using imagesetpixel().

One of the few reasons to change your image data into a binary stream is to hide additional data in the lower order of binary bits during steganography - altering the color of each pixel at a level not discernable to the human eye.

Check http://www.php.net/manual/en/function.imagesetpixel.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM