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.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看