如何将Base64图像保存到images文件夹上的图像文件

I have a JQUERY image cropping plugin that stores a cropped result as Base64/JPEG. I'd like to save that Base64 IMG as an actual JPG in a folder called IMAGES in the root.

The example screenshot below shows you the Base64 image that I would like saved as file. The SAVE button doesn't do anything right now, but should perform my desired function.

I assume there will be some PHP as well that does the saving to IMAGES part. It would also be good if it saves the image file with some random name (IE - not image.jpg, but image_random52.jpg)

<input id="save_to_file" type="button" value="Save" onClick="MaybeSomethingShouldGoHERE???()"></div>

enter image description here

Also, here is the relevant PHP code that generated that Base64 Image.

$resizedImage = imagecreatetruecolor($imgW, $imgH);
imagecopyresampled($resizedImage, $source_image, 0, 0, 0, 0, $imgW,
            $imgH, $imgInitW, $imgInitH);
$dest_image = imagecreatetruecolor($cropW, $cropH);
imagecopyresampled($dest_image, $resizedImage, 0, 0, $imgX1, $imgY1, $cropW,
            $cropH, $cropW, $cropH);
ob_start();
imagejpeg($dest_image, null, $jpeg_quality);
$imgData = ob_get_clean();
ob_end_clean();
$response = array(
    "status" => 'success',
    "url" => 'data:'.$what['mime'].';base64,'.base64_encode($imgData),
  );

 echo json_encode($response);

UPDATED PHP CODE

$response = array(
    "status" => 'success',
    "url" => 'data:'.$what['mime'].';base64,'.base64_encode($imgData),
    $final_output = 'data:'.$what['mime'].';base64,'.base64_encode($imgData)
  );


   $decoded=base64_decode($final_output);

file_put_contents('newImage.JPG',$decoded);
//leave it to you to randomize the filename.
doulu4233
doulu4233 如果我从Chrome浏览器保存AS,这将输出相同大小的文件,但该文件只是说损坏?我的$final_output怎么了?
4 年多之前 回复
dqjfw40446
dqjfw40446 我想我几乎拥有它。我能够解码并输出JPG文件,但是当我打开文件时它已经损坏了。请参阅添加的代码。谢谢
4 年多之前 回复

1个回答

OK, Here was my solution. I didn't actually use OnClick of the Save button, but performed the save directly from my cropping PHP file. I added the last 3 lines staring from $final_output. This allowed me to save file to folder.

Before I didn't understand the logic, but I now do.

  "status" => 'success',
    "url" => 'data:'.$what['mime'].';base64,'.base64_encode($imgData),

$final_output = base64_encode($imgData)

  );

//Decode and Save Image 
$decoded=base64_decode($final_output);
file_put_contents($output_filename.$type,$decoded);
//leave it to you to randomize the filename.
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问