Programming

Base64 문자열을 이미지 파일로 변환 하시겠습니까?

procodes 2020. 6. 29. 21:18
반응형

Base64 문자열을 이미지 파일로 변환 하시겠습니까?


base64 이미지 문자열을 이미지 파일로 변환하려고합니다. 이것은 내 Base64 문자열입니다.

http://pastebin.com/ENkTrGNG

다음 코드를 사용하여 이미지 파일로 변환 :

function base64_to_jpeg( $base64_string, $output_file ) {
    $ifp = fopen( $output_file, "wb" ); 
    fwrite( $ifp, base64_decode( $base64_string) ); 
    fclose( $ifp ); 
    return( $output_file ); 
}

$image = base64_to_jpeg( $my_base64_string, 'tmp.jpg' );

하지만의 오류가 발생했습니다. invalid image여기서 무엇이 잘못 되었습니까?


문제는 data:image/png;base64,인코딩 된 내용에 포함되어 있다는 것 입니다. 이로 인해 base64 함수가이를 디코딩 할 때 잘못된 이미지 데이터가 생성됩니다. 문자열을 디코딩하기 전에 함수에서 해당 데이터를 제거하십시오.

function base64_to_jpeg($base64_string, $output_file) {
    // open the output file for writing
    $ifp = fopen( $output_file, 'wb' ); 

    // split the string on commas
    // $data[ 0 ] == "data:image/png;base64"
    // $data[ 1 ] == <actual base64 string>
    $data = explode( ',', $base64_string );

    // we could add validation here with ensuring count( $data ) > 1
    fwrite( $ifp, base64_decode( $data[ 1 ] ) );

    // clean up the file resource
    fclose( $ifp ); 

    return $output_file; 
}

data:image/png;base64,이미지 데이터의 시작 부분에 표시된 부분을 제거해야합니다 . 그 후 실제 base64 데이터가옵니다.

base64,( base64_decode()데이터 를 호출하기 전에) 까지 모든 것을 제거 하면 괜찮을 것입니다.


내가 사용하는 쉬운 방법 :

file_put_contents($output_file, file_get_contents($base64_string));

file_get_contentsdata : // URI를 포함하여 URI에서 데이터를 읽을 수 있기 때문에 잘 작동 합니다.


아마도 이것처럼

function save_base64_image($base64_image_string, $output_file_without_extension, $path_with_end_slash="" ) {
    //usage:  if( substr( $img_src, 0, 5 ) === "data:" ) {  $filename=save_base64_image($base64_image_string, $output_file_without_extentnion, getcwd() . "/application/assets/pins/$user_id/"); }      
    //
    //data is like:    data:image/png;base64,asdfasdfasdf
    $splited = explode(',', substr( $base64_image_string , 5 ) , 2);
    $mime=$splited[0];
    $data=$splited[1];

    $mime_split_without_base64=explode(';', $mime,2);
    $mime_split=explode('/', $mime_split_without_base64[0],2);
    if(count($mime_split)==2)
    {
        $extension=$mime_split[1];
        if($extension=='jpeg')$extension='jpg';
        //if($extension=='javascript')$extension='js';
        //if($extension=='text')$extension='txt';
        $output_file_with_extension=$output_file_without_extension.'.'.$extension;
    }
    file_put_contents( $path_with_end_slash . $output_file_with_extension, base64_decode($data) );
    return $output_file_with_extension;
}

그것은 오래된 스레드이지만 동일한 확장자를 가진 이미지를 업로드하려는 경우

    $image = $request->image;
    $imageInfo = explode(";base64,", $image);
    $imgExt = str_replace('data:image/', '', $imageInfo[0]);      
    $image = str_replace(' ', '+', $imageInfo[1]);
    $imageName = "post-".time().".".$imgExt;
    Storage::disk('public_feeds')->put($imageName, base64_decode($image));

laravel의 파일 시스템에서 'public_feeds'를 만들 수 있습니다.

   'public_feeds' => [
        'driver' => 'local',
        'root'   => public_path() . '/uploads/feeds',
    ],

if($_SERVER['REQUEST_METHOD']=='POST'){
$image_no="5";//or Anything You Need
$image = $_POST['image'];
$path = "uploads/".$image_no.".png";

$status = file_put_contents($path,base64_decode($image));
if($status){
 echo "Successfully Uploaded";
}else{
 echo "Upload failed";
}
}

이 코드는 저에게 효과적이었습니다.

<?php
$decoded = base64_decode($base64);
$file = 'invoice.pdf';
file_put_contents($file, $decoded);

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
?>


$datetime = date("Y-m-d h:i:s");
$timestamp = strtotime($datetime);
$image = $_POST['image'];
$imgdata = base64_decode($image);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$temp=explode('/',$mime_type);
$path = "uploads/$timestamp.$temp[1]";
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded->>> $timestamp.$temp[1]";

이미지 처리에 충분합니다. 데브 카란 샤르마 덕분에 특별한 감사

참고 URL : https://stackoverflow.com/questions/15153776/convert-base64-string-to-an-image-file

반응형