繁体   English   中英

如何在PHP中使用不同的名称保存相同的图像?

[英]How to save same image with different names in PHP?

我写了一个从.jpg图像创建缩略图的功能。 但是我想做的是每当调用该函数时,应将同一图像保存为同一目的地的1.jpg,2.jpg,3.jpg。

我使用了Sessions和静态变量概念,但没有成功。

这是我的代码。 这是thumbsave.php文件

<?php
session_start();
$_SESSION['sid']=$k=1;
function createThumb($fpath)//fpath will be passed here as parameter.
{
$ims = imagecreatefromjpeg($fpath);
$imd = imagecreatetruecolor(100, 100);

imagecopyresized($imd, $ims, 0, 0, 0, 0, 100, 100, imagesx($ims), 
imagesy($ims));
imagejpeg($imd,"saveimages/" . $_SESSION['sid'] . ".jpg");
$_SESSION['sid'] = $_SESSION['sid'] + 1;
imagedestroy($ims);
imagedestroy($imd);

echo "Thumbnail Created and Saved at the Destination";

}

?>

这是我的dynamicthumb.php代码

<?php
include("include/thumbsave.php");
createThumb("imgs/m1.jpeg");
 ?>

因此,当我运行dynamicthumb.php文件时,存储在imgs文件夹中的图像必须存储在saveimages文件夹中。 但是这里只保存了1张图像,不会生成2.jpg,3.jpg之类的多个副本。

这是负责将图像保存到文件的行:

imagejpeg($imd,"saveimages/" . $_SESSION['sid'] . ".jpg");

您可以将其更新为使用$fpath而不是$_SESSION['sid']

imagejpeg($imd, $fpath);

但是请注意 ,您的路径应以.jpg结尾。

如果您肯定,则可以使用file_exists循环,缩略图的名称将始终为数字:

function createThumb($fpath)
{
    $ims = imagecreatefromjpeg($fpath);
    $imd = imagecreatetruecolor(100, 100);

    imagecopyresized($imd, $ims, 0, 0, 0, 0, 100, 100, imagesx($ims), imagesy($ims));

    $thumb = 1;
    while ( file_exists('saveimages/'. $thumb .'.jpg') ) { $thumb++; }

    imagejpeg($imd,'saveimages/'. $thumb .'.jpg');
    imagedestroy($ims);
    imagedestroy($imd);

    echo 'Thumbnail Created and Saved at the Destination as '. $thumb .'.jpg';
}

但是我对您要的内容背后的逻辑表示怀疑...因为这表明您创建的每个缩略图都只是一个序号,全部存储在同一目录中?

使用counter db字段或文件可能会带来更好的运气,因为在具有数千个且不断增长的文件夹中执行file_exists可能会影响性能。

因此,基于文件的counter解决方案可能是:

function createThumb($fpath)
{
    $ims = imagecreatefromjpeg($fpath);
    $imd = imagecreatetruecolor(100, 100);

    imagecopyresized($imd, $ims, 0, 0, 0, 0, 100, 100, imagesx($ims), imagesy($ims));

    $thumb  = file_get_contents('saveimages/thumbcount.txt');
    $thumb++; file_put_contents('saveimages/thumbcount.txt',$thumb);

    imagejpeg($imd,'saveimages/'. $thumb .'.jpg');
    imagedestroy($ims);
    imagedestroy($imd);

    echo 'Thumbnail Created and Saved at the Destination as '. $thumb .'.jpg';
}

只要确保将thumbcount.txt1 ,即可开始。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM