programing

Base64 데이터 URI에서 PNG 이미지 서버 측을 저장하는 방법

bestcode 2022. 9. 25. 00:30
반응형

Base64 데이터 URI에서 PNG 이미지 서버 측을 저장하는 방법

Nihilogic의 "Canvas2Image" JavaScript 툴을 사용하여 캔버스 그림을 PNG 이미지로 변환하고 있습니다.지금 필요한 것은 이 툴이 생성하는 base64 문자열을 PHP를 사용하여 서버상의 실제 PNG 파일로 변환하는 것입니다.

즉, 현재 Canvas2Image를 사용하여 클라이언트 측에서 파일을 생성한 후 Base64 인코딩 데이터를 가져와 AJAX를 사용하여 서버로 전송합니다.

// Generate the image file
var image = Canvas2Image.saveAsPNG(canvas, true);   

image.id = "canvasimage";
canvas.parentNode.replaceChild(image, canvas);

var url = 'hidden.php',
data = $('#canvasimage').attr('src');

$.ajax({ 
    type: "POST", 
    url: url,
    dataType: 'text',
    data: {
        base64data : data
    }
});

이 시점에서 "hidden.php"는 다음과 같은 데이터 블록을 수신합니다.image/png;base64,iVBORw0KGOAAAANSUhEUGABE...

이제부터는 정말 당황스럽네요.제가 읽은 바로는 PHP의 image create from string 함수를 사용해야 한다고 생각합니다만, 실제로 base64 인코딩 문자열에서 PNG 이미지를 생성하여 서버에 저장하는 방법을 잘 모르겠습니다.도와주세요!

이 문자열에서 Base64 이미지 데이터를 추출하여 디코딩한 후 디스크에 저장할 수 있습니다.이미 png이기 때문에 GD는 필요 없습니다.

$data = 'data:image/png;base64,AAAFBfj42Pj4';

list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);

file_put_contents('/tmp/image.png', $data);

원라이너로서:

$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));

에러를 추출, 디코딩, 체크하는 효율적인 방법은 다음과 같습니다.

if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
    $data = substr($data, strpos($data, ',') + 1);
    $type = strtolower($type[1]); // jpg, png, gif

    if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
        throw new \Exception('invalid image type');
    }
    $data = str_replace( ' ', '+', $data );
    $data = base64_decode($data);

    if ($data === false) {
        throw new \Exception('base64_decode failed');
    }
} else {
    throw new \Exception('did not match data URI with image data');
}

file_put_contents("img.{$type}", $data);

이것을 시험해 보세요.

file_put_contents('img.png', base64_decode($base64string));

file_put_docs

공간을 플러스 기호로 대체해야 했습니다.str_replace(' ', '+', $img);이 일을 할 수 있게 말이야

여기 전체 코드가 있습니다.

$img = $_POST['img']; // Your data 'data:image/png;base64,AAAFBfj42Pj4';
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents('/tmp/image.png', $data);

도움이 됐으면 좋겠다.

논의된 토픽은 RFC 2397 - "데이터" URL 스킴(https://www.rfc-editor.org/rfc/rfc2397)에 기재되어 있습니다.

이러한 이유로 PHP는 이러한 데이터를 처리하는 네이티브 방법을 가지고 있습니다. - "data: stream wrapper"(http://php.net/manual/en/wrappers.data.php)

따라서 PHP 스트림으로 데이터를 쉽게 조작할 수 있습니다.

$data = 'data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7';

$source = fopen($data, 'r');
$destination = fopen('image.gif', 'w');

stream_copy_to_stream($source, $destination);

fclose($source);
fclose($destination);

@dre010의 아이디어를 바탕으로 PNG, JPG, JPEG, GIF 등 모든 이미지 타입에 대응하는 다른 기능으로 확장하여 파일명에 고유한 이름을 붙였습니다.

이 함수는 이미지 데이터와 이미지 유형을 구분합니다.

function base64ToImage($imageData){
    $data = 'data:image/png;base64,AAAFBfj42Pj4';
    list($type, $imageData) = explode(';', $imageData);
    list(,$extension) = explode('/',$type);
    list(,$imageData)      = explode(',', $imageData);
    $fileName = uniqid().'.'.$extension;
    $imageData = base64_decode($imageData);
    file_put_contents($fileName, $imageData);
}

위의 솔루션은 이미지가 jpeg 파일인지에 따라 달라집니다.내가 사용한 일반적인 솔루션

$img = $_POST['image'];
$img = substr(explode(";",$img)[1], 7);
file_put_contents('img.png', base64_decode($img));

총 우려 사항:

$data = 'data:image/png;base64,AAAFBfj42Pj4';

// Extract base64 file for standard data
$fileBin = file_get_contents($data);
$mimeType = mime_content_type($data);

// Check allowed mime type
if ('image/png'==$mimeType) {
    file_put_contents('name.png', $fileBin);
}

http://php.net/manual/en/wrappers.data.php

http://php.net/manual/en/function.mime-content-type.php

일직선 솔루션

$base64string = 'data:image/png;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7';
file_put_contents('img.png', base64_decode(explode(',',$base64string)[1]));

이 코드는 아래 코드를 확인하는 데 도움이 됩니다.

<?php
define('UPLOAD_DIR', 'images/');
$image_parts = explode(";base64,", $_POST['image']);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = UPLOAD_DIR . uniqid() . '.png';
file_put_contents($file, $image_base64);
?>

draw010의 예를 바탕으로 이해하기 쉬운 예를 만들었습니다.

imagesaver("data:image/jpeg;base64,/9j/4AAQSkZJ"); //use full base64 data 

function imagesaver($image_data){

    list($type, $data) = explode(';', $image_data); // exploding data for later checking and validating 

    if (preg_match('/^data:image\/(\w+);base64,/', $image_data, $type)) {
        $data = substr($data, strpos($data, ',') + 1);
        $type = strtolower($type[1]); // jpg, png, gif

        if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
            throw new \Exception('invalid image type');
        }

        $data = base64_decode($data);

        if ($data === false) {
            throw new \Exception('base64_decode failed');
        }
    } else {
        throw new \Exception('did not match data URI with image data');
    }

    $fullname = time().$type;

    if(file_put_contents($fullname, $data)){
        $result = $fullname;
    }else{
        $result =  "error";
    }
    /* it will return image name if image is saved successfully 
    or it will return error on failing to save image. */
    return $result; 
}

이거 먹어봐...

$file = $_POST['file']; //your data in base64 'data:image/png....';
$img = str_replace('data:image/png;base64,', '', $file);
file_put_contents('img/imag.png', base64_decode($img));

PHP는 이미 공평한 처리 기준 64 -> 파일 변환을 가지고 있습니다.

난 이런 식으로 코딩하곤 했어

$blob=$_POST['blob']; // base64 coming from an url, for example

//Now, let's save the image file:

file_put_contents('myfile.png',file_get_contents($blob));

파일명이 $filename이고 base64 인코딩된 문자열이 $testfile my oneliner에 있다고 가정하면 다음과 같습니다.

file_put_contents($filename,base64_decode(explode(',', $testfile)[1]))

이 기능은 동작합니다.여기에는 base64 문자열을 유지하는 photo 파라미터와 새로운 이미지 저장 중에 링크를 해제하는 기존 이미지가 이미 있는 경우 기존 이미지 디렉토리에 대한 경로도 포함됩니다.

 public function convertBase64ToImage($photo = null, $path = null) {
    if (!empty($photo)) {
        $photo = str_replace('data:image/png;base64,', '', $photo);
        $photo = str_replace(' ', '+', $photo);
        $photo = str_replace('data:image/jpeg;base64,', '', $photo);
        $photo = str_replace('data:image/gif;base64,', '', $photo);
        $entry = base64_decode($photo);
        $image = imagecreatefromstring($entry);

        $fileName = time() . ".jpeg";
        $directory = "uploads/customer/" . $fileName;

        header('Content-type:image/jpeg');

        if (!empty($path)) {
            if (file_exists($path)) {
                unlink($path);
            }
        }

        $saveImage = imagejpeg($image, $directory);

        imagedestroy($image);

        if ($saveImage) {
            return $fileName;
        } else {
            return false; // image not saved
        }
    }
}

간단합니다.

js 프레임워크, ajax 요청 또는 모바일 애플리케이션(클라이언트 측) 내에서 파일을 업로드하려고 한다고 가정합니다.

  1. 먼저 base64 인코딩된 문자열을 포함하는 데이터 속성을 전송합니다.
  2. 서버 측에서 디코딩하여 로컬 프로젝트 폴더에 저장해야 합니다.

PHP를 사용하여 수행하는 방법

<?php 

$base64String = "kfezyufgzefhzefjizjfzfzefzefhuze"; // I put a static base64 string, you can implement you special code to retrieve the data received via the request.

$filePath = "/MyProject/public/uploads/img/test.png";

file_put_contents($filePath, base64_decode($base64String));

?>

이미지 이름을 임의로 변경하고 이미지 경로와 이미지 자체를 모두 데이터베이스에 blob으로 저장하려는 경우 이 솔루션이 도움이 됩니다.웹 사이트 사용자는 원하는 만큼의 이미지를 저장할 수 있으며, 이미지의 이름은 보안을 위해 임의로 변경됩니다.

Php 코드

이미지 이름으로 사용할 랜덤 바커를 생성합니다.

function genhash($strlen) {
        $h_len = $len;
        $cstrong = TRUE;
        $sslkey = openssl_random_pseudo_bytes($h_len, $cstrong);
        return bin2hex($sslkey);
}
$randName = genhash(3); 
#You can increase or decrease length of the image name (1, 2, 3 or more).

이미지에서 이미지 데이터 확장 및 base_64 부품(데이터 다음 부분:image/png;base64)을 가져옵니다.

$pos  = strpos($base64_img, ';');
$imgExten = explode('/', substr($base64_img, 0, $pos))[1];
$extens = ['jpg', 'jpe', 'jpeg', 'jfif', 'png', 'bmp', 'dib', 'gif' ];

if(in_array($imgExten, $extens)) {

   $imgNewName = $randName. '.' . $imgExten;
   $filepath = "resources/images/govdoc/".$imgNewName;
   $fileP = fopen($filepath, 'wb');
   $imgCont = explode(',', $base64_img);
   fwrite($fileP, base64_decode($imgCont[1]));
   fclose($fileP);

}

# => $filepath <= This path will be stored as blob type in database.
# base64_decoded images will be written in folder too.

# Please don't forget to up vote if you like my solution. :)

언급URL : https://stackoverflow.com/questions/11511511/how-to-save-a-png-image-server-side-from-a-base64-data-uri

반응형