扫描目录并从现有图像创建缩略图 [英] Scanning directory and creating thumbnails from already exisiting images

查看:78
本文介绍了扫描目录并从现有图像创建缩略图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要用此代码完成的工作是,首先扫描图像后的目录,然后拍摄一个图像,并在图像大于170x170时从中创建缩略图.我遇到的问题是,当我尝试加载新文件时,它无法按预期工作.

What I'm trying to accomplish with this code is, first it scans a directory after images, then it takes one image and create a thumbnail out of it if its bigger than 170x170. The problem I'm having is when I try to load the new file it doesn't work quite as expected.

<?php
foreach (glob('img/*.png') as $f) {
    $list[filemtime($f) . '-' . $f] = $f;
}   

$keys = array_keys($list);      
sort($keys);

$picOne = $list[array_pop($keys)];
$picTwo = $list[array_pop($keys)];
$picThree = $list[array_pop($keys)];
$picFour = $list[array_pop($keys)];

list($width, $height) = getimagesize($picOne);
if ($width > 170 && $height > 170) {
    $thumb = imagecreatetruecolor(170, 170);
    $source = imagecreatefrompng($picOne);
    imagecopyresized($thumb, $source, 0, 0, 0, 0, 170, 170, $width, $height);
    $path = $picOne."_170x170.png";
    imagepng($thumb, $path);
}

echo '<a href="'.$picOne.'" /><img width=170 height=170 src="'.$picOne.'" /></a>&nbsp;&nbsp;'; 
echo '<a href="'.$picTwo.'" /><img width=170 height=170 src="'.$picTwo.'" /></a>&nbsp;&nbsp;'; 
echo '<a href="'.$picThree.'" /><img width=170 height=170 src="'.$picThree.'" /></a>&nbsp;&nbsp;';  
echo '<a href="'.$picFour.'" /><img width=170 height=170 src="'.$picFour.'" /></a>';   

?>

此代码应该创建一个新文件,对吧?

This code should make a new file, right?

$path = $picOne."_170x170.png";
imagepng($thumb, $path)

那部分肯定可以正常工作,但是$ picOne被添加了_170x170.png,我不明白为什么.我想我所做的只是使用$ picOne名称+ _170x170.png创建一个新文件,但是$ picOne也会得到它.

That part works fine sure but $picOne gets _170x170.png added to it and I don't understand why. What I think I've done is just to create a new file with the $picOne name + _170x170.png but instead $picOne gets it as well.

有人可以帮助我修复此代码或解释我需要做什么才能使其正常工作吗?

Can anyone help me fix this code or explain what I need to do to get it to work?

这基本上是我要做的事情: 1.扫描目录. 2.拍摄图像并从中创建缩略图. 3.输出缩略图.

Here's what I'm trying to do basically: 1. Scan a directory. 2. Take an image and create a thumbnail from it. 3. Output the thumbnail.

推荐答案

出现问题的原因是您不是在创建新文件,而是在覆盖现有文件.要在每次尝试使用此循环时创建新文件:

The reason you are having issue is that you are not creating new file but overwriting existing file. To create new file every time you try using this loop :

    $path =  $picOne."_170x170.png";

    $x = 0 ;
    while (file_exists($path))
    {
        $path = $picOne ."-" . $x . ."_170x170.png"; 
        $x++;
    }

这将始终为您提供一个新的文件名,您可以将其放在一个简单的函数中.

This would always give you a new file name all the time and you can put it in a simple function.

这篇关于扫描目录并从现有图像创建缩略图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆