doulv8162 2014-07-17 21:17
浏览 61

通过php在本地保存dataURL图像

I'm making a PNG image file from a dataURL string (thanks to the example from The PHP manual). I'd like this code to open the "Download file" dialog in the browser, so users can save this image locally, but calling the function imagepng() saves the image to my server instead. Am I using the wrong function when calling imagepng()? I'm trying to trigger a download by changing the headers, but it's still saving to the server.

<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
    . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
    . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
    . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';

$data = base64_decode($data);

$im = imagecreatefromstring($data);

// set the headers, to trigger a download
header('Content-Disposition: attachment; filename="image.png"');
header('Content-Type: image/png');
imagepng($im, 'test_2.png');
imagedestroy($im);
?>

Also, I'm calling the PHP via the following JavaScript, (not sure if this is relevant to the results I'm getting)

$.ajax({ 
    type: "POST", 
    url: "php/downloadimg.php",
    dataType: 'text',
    data: {
        data : finishedImage.src
    }
})
  • 写回答

2条回答 默认 最新

  • dragon7713 2014-07-17 21:24
    关注

    just call the imagepng function without the second parameter. if you follow the imagepng documentation you read that filling in the second parameter the image is saved to this filename.

    pass only the image resource to the function and the raw image are send to the client.

    http://php.net/manual/de/function.imagepng.php

    header('Content-Disposition: attachment; filename="image.png"');
    header('Content-Type: image/png');
    imagepng($im);
    imagedestroy($im);
    

    if you use php only files don't use the php close tag ?> to avoid leaked whitespaces and messed up your output stream.

    评论

报告相同问题?

悬赏问题

  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划