【问题标题】:How to download image from php file with javascript如何使用 javascript 从 php 文件中下载图像
【发布时间】:2016-06-09 17:11:30
【问题描述】:

I got the code from this link

但我有一个问题。我从 php 文件中提取图像如下:-

<img src="http://localhost/wordpress/image.php" class="downloadable" id="mainimage"/>

然后我想用 javascript 下载它,如下所示:-

$('img.downloadable').each(function(){
  var $this = $(this);
  $this.wrap('<a href="' + $this.attr('src') + '" download />')
});

问题是它下载 php 文件,但我想将它下载为 PNG。

image.php 的摘录如下:-

header ("Content-type: image/png");
$userinput = $_GET["user_input"];
$image=imagecreatefrompng('myimages/***image.png***'); 
$font_file = 'fonts/PR8Charade.ttf';
$col1 = imagecolorallocate($image, 129, 125,11);
    $text_size1 = 36;
    $xposition1 = 245;
    $yposition1 = 380;
    $angeldirection1 = 50;
    imagettftext($image, $text_size1, $angeldirection1, $xposition1, $yposition1, $col1, $font_file, $userinput);
ImagePng($image);
imagedestroy($image);

我想从 image.php 下载 image.png 文件。

【问题讨论】:

  • 您需要输出一个内容处置标头,它允许您为“下载”指定一个文件名。由于您没有,浏览器只需选择最明显的文件名 - 您正在下载的 url 中的文件名,即image.php
  • 创建图片后,您可以将图片url发送给客户端,然后window.open(imageUrl)将下载您的图片

标签: javascript php jquery html


【解决方案1】:
<?php
//path to png image
$file = 'picture.png';

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;
}
?>

【讨论】:

猜你喜欢
  • 2016-03-18
  • 2021-07-31
  • 2012-07-15
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 2020-10-07
  • 2011-11-16
  • 1970-01-01
相关资源
最近更新 更多