Redimensionare imagini

PEAR, Smarty, ADOdb, OOP, PHP 5, XML, UML, Şabloane de proiectare, PHP-GTK.

Moderatori: coditza, Emil, Moderatori

valygreavu
New Member
Mesaje: 1
Membru din: Lun Iul 26, 2004 6:37 pm
Localitate: Iasi
Contact:

Redimensionare imagini

Mesajde valygreavu » Lun Iul 26, 2004 6:44 pm

Salutare tuturor,

Poate sa-mi spuna cineva daca pot face redimensionarea tuturor imaginilor dintr-un director?

Daca da va ramin purutea indatorat :-)

De exemplu am un directoru /images/auto/
in el am un numar de fisiere JPG de diferite dimensiuni. Este posibil ca printr-o pagina PHP sa pot schimba automat dimensiunea tuturor imaginilor in 40KB sau mai putin?

Va multumesc!



coditza
Senior Member
Mesaje: 298
Membru din: Vin Ian 23, 2004 7:30 pm
Localitate: cluj-napoca

Mesajde coditza » Lun Iul 26, 2004 6:45 pm

cu GD sau cu iamgemagik (despre care am observat ca se descurca mai bine la multe imagini)
function foo() { foo(); }

Avatar utilizator
stealth
Senior Member
Mesaje: 308
Membru din: Lun Iun 21, 2004 9:36 am
Localitate: Timisoara
Contact:

Mesajde stealth » Mar Iul 27, 2004 5:17 am

nu stiu daca exista vreo functie in GD care te ajuta sa redimensionezi o imagine in favoarea dimensiunii de stocare.
Pentru redimensionare normala a unei imagini folosind GD citeste tutorialul de la adresa:

Pe mine m-a ajutat mult.

Radical
Senior Member
Mesaje: 327
Membru din: Lun Feb 16, 2004 2:40 pm
Localitate: Bucuresti
Contact:

Mesajde Radical » Mar Iul 27, 2004 11:57 am


darkwish02
PHPRomania Supporter
Mesaje: 18
Membru din: Mie Aug 04, 2004 1:25 pm
Localitate: Craiova
Contact:

am eu un script ....

Mesajde darkwish02 » Mie Aug 04, 2004 1:31 pm

Carpe diem baby :)

taipan
Junior Member
Mesaje: 44
Membru din: Vin Sep 24, 2004 3:47 pm

Mesajde taipan » Mar Oct 12, 2004 4:08 pm

Uite aici clasa mea de file poate te inspiri din ea :).
Ideea este ca face cam tot (verificare,redimensionare, upload, stocare cale imagine/fisier in baza, verifica daca directorul de stocare exista etc);

[php]class files {
/*
The function will allow me to perform operations with files and archives.
Main Methods:
addFile -> Upload a file into a location
delFile -> Delete a file from a location
modFile -> Edit a file from a location
resFile -> Resize a file (available only for images)
*/

//Class variable declaration
var $filename; //<- file full name
var $filesize; //<- here i will load file size in kb
var $filetype; //<- here i will load extension
var $filebase; //<- file name without extension
var $filelocation; //<- were the file will be stored
var $fileallowed; //<- allowed file types
var $filetemp; //<- file name of temporary file

var $datamodule; //<- here i will store the database connection link
var $errorout; //<- here i will store the error management system
var $alert;



//Class constructor
function files() {
//Here i will initialise the engine variables (database and error management system)
$this->fileallowed = array(0 =>array("gif", "jpg", "jpeg", "png"),1=> array("zip", "rar"));
$this->datamodule = new dataserv();
}

//Internal methods
function errorOut($message) {
/*
This is an error function, you may replace the code with your config
*/

echo $message;
exit;
}

function inFileDetails($filename) {
//I will load class variables with needed details
if(strlen($filename) < 5) {
$this->errorOut('Please insert a valid file name.<br>');
}

$tmpFile = pathinfo($filename);
$this->filebase = $tmpFile['basename'];
$this->filetype = strtolower($tmpFile['extension']);
//Check the extension details
$tmpIndex = 0; $tmpFound = 0;
$tmpIndex = sizeof($this->fileallowed);
for($i=0; $i<$tmpIndex; $i++) {
foreach($this->fileallowed[$i] as $key=>$value) {
if(strcasecmp($this->filetype,$value) == 0) {
$tmpFound=1;
}
}
}
if($tmpFound == 0) {
$this->errorOut('The file extension is not allowed.<br>');
}
}

function inFileTarget($target) {
//I will check the target directory existance and permission
if(is_dir($target)) {
if(!is_readable($target)) {
$this->errorOut('The directory could not be open for reading.<br>');
}
if(!is_writable($target)) {
$this->errorOut('The directory could not be open for writting.<br>');
}
}
else {
$this->errorOut('The directory does not exists.<br>');
}
}


//Public methods
function inFileLimit ($filesize,$limitsize) {
if($filesize > $limitsize) {
$this->errorOut('The filesize exceed the maximum limit.<br>');
}
}

function sqlFile($tablename,$itemid,$column) {
/*
This function will upload in database the file details (location)
*/
$data = $this->filename;
//Getting table primary key
$sql="SHOW INDEX FROM ".$tablename;
$this->datamodule->engQuery($sql);
$row=mysql_fetch_array($this->datamodule->result,MYSQL_ASSOC);
$primaryKey=$row['Column_name'];
mysql_free_result($this->datamodule->result);

//Now performing the test <- if the record exists i will make update, otherwise i will make insert
$sql="select count($primaryKey) as itemNumber from $tablename where $primaryKey=$itemid";
$this->datamodule->engQuery($sql);
$row=mysql_fetch_array($this->datamodule->result,MYSQL_ASSOC);
$itemNumber = $row['itemNumber'];
mysql_free_result($this->datamodule->result);
if($itemNumber !=0){
$sql="update $tablename set $column='{$data}' where $primaryKey=$itemid";
$this->datamodule->engQuery($sql);
}
else{
$sql="insert into $tablename ($column) values ('{$data}')";
$this->datamodule->engQuery($sql);
}
}
function addFile($location,$filename,$filetemp) {
//Variable declaration
$this->filename = $filename;
$this->filelocation = $location;
$this->filetemp = $filetemp;
$tmpLocation="";
$tmpLocation=$this->filelocation.$this->filename;

$this->inFileTarget($this->filelocation);
$this->inFileDetails($this->filename);

//Verify if a other file has same name
if(file_exists($tmpLocation)) {
$this->errorOut('This file name is already used by another file');
}

//Uploading the file
if(is_uploaded_file($this->filetemp)) {
move_uploaded_file($this->filetemp, $tmpLocation);
chmod($tmpLocation, 0755);
}
}

function delFile($location,$filename) {
/*
The function will delete a file from specified location
*/

//Variable declaration
$this->filename = $filename;
$this->filelocation = $location;
$this->inFileTarget($this->filelocation);
$tmpLocation ='';
$tmpLocation = $location.$filename;

//Deleting the file
chmod($tmpLocation, 0755);
$fileDeleted = unlink($tmpLocation);
if(!$fileDeleted) {
$this->errorOut('Cannot delete the file.<br>');
}
}

function delFileNoError($location,$filename) {
/*
The function will delete a file from specified location
*/

//Variable declaration
$this->filename = $filename;
$this->filelocation = $location;
$this->inFileTarget($this->filelocation);
$tmpLocation ='';
$tmpLocation = $location.$filename;

//Deleting the file
chmod($tmpLocation, 0755);
$fileDeleted = @unlink($tmpLocation);
}

function modFile($location,$filename,$filetemp) {
/*
Editable function.
It will replace a file with a new one
*/

//Variable declaration
$this->filename = $filename;
$this->filelocation = $location;
$this->filetemp = $filetemp;
$tmpLocation="";
$tmpLocation=$this->filelocation.$this->filename;

$this->inFileTarget($this->filelocation);
$this->inFileDetails($this->filename);

//Updating the file
if(is_uploaded_file($this->filetemp)) {
move_uploaded_file($this->filetemp, $tmpLocation);
chmod($tmpLocation, 0755);
}
}

function resFile($width,$height,$proportion) {
/*
This function will resize an image and depending on the PHP version i will
also enable the gif resising, otherwise i will let the gif file as it is.

$proportion <- if is set to 1 this will force the resising process to maintain
the image scale
*/
$tmpLocation="";
$tmpLocation=$this->filelocation.$this->filename;

if(!in_array($this->filetype,$this->fileallowed[0])) {
$this->errorOut("Invalid extension for an image.<br>");
}

if(file_exists($tmpLocation)) {
if(strcasecmp($this->filetype,'jpg')==0 or strcasecmp($this->filetype,'jpeg')==0) {
$img=@imagecreatefromjpeg($tmpLocation);
}
elseif(strcasecmp($this->filetype,'png')==0) {
$img=@imagecreatefrompng($tmpLocation);
}
elseif(strcasecmp($this->filetype,'gif')==0) {
$img=@imagecreatefromgif($tmpLocation);
}
if ($img) {
# Get image size and scale ratio
$imgWidth = imagesx($img);
$imgHeight = imagesy($img);
$scale = min($width/$imgWidth, $height/$imgHeight);
if ($scale < 1) {
if($proportion == 1) {
$new_width = floor($scale*$imgWidth);
$new_height = floor($scale*$imgHeight);
}
else {
$new_width = $width;
$new_height = $height;
}
# Create a new temporary image
$tmp_img = imagecreatetruecolor($new_width, $new_height);
$bgc = imagecolorallocate($tmp_img, 255, 255, 255);
imagefilledrectangle($tmp_img, 0, 0, $new_width, $new_height, $bgc);
# Copy and resize old image into new image
$resized=imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $imgWidth, $imgHeight);
switch ($this->filetype) {
case 'jpg':
imagejpeg($tmp_img,$tmpLocation,80);
break;
case 'gif':
{
if (function_exists("imagegif")){
imagegif($tmp_img,$tmpLocation);
}
}
break;
case 'png':
imagepng($tmp_img,$tmpLocation);
break;
}
imagedestroy($img);
imagedestroy($tmp_img);
}
}
}
}
}[/php]
Orice problema se rezolva cu o grenada.

apann
Average Member
Mesaje: 93
Membru din: Lun Mai 17, 2004 1:47 pm

Mesajde apann » Mie Oct 13, 2004 10:46 am


taipan
Junior Member
Mesaje: 44
Membru din: Vin Sep 24, 2004 3:47 pm

Mesajde taipan » Vin Oct 15, 2004 12:19 pm

Orice problema se rezolva cu o grenada.

apann
Average Member
Mesaje: 93
Membru din: Lun Mai 17, 2004 1:47 pm

Mesajde apann » Lun Oct 18, 2004 11:30 am

Da, dar, nu mai vad rostul exemplului tau de 266 de linii pastat aici din moment ce nu o sa mearga.
In al doilea rand, omul incearca sa faca redimensionarea tuturor imaginilor dintr-un director.
Care este rostul acelor sql query din codul tau?

Poate era mai bine asa:
[php]
<?php
$d = dir("img/");
while (false !== ($entry = $d->read())) {
if($entry!="." && $entry!=".."){
$v=explode(".",$entry);
print_r($v);

convert("img/$entry",$v[0],$v[1]);

echo $entry . "\n";
} // if
} // while
$d->close();


function convert($file,$filename,$ext){
// small:
$dfile = "tmp/" . $filename . "_100x200." . $ext;
createTh($file,$dfile,100,200,$ext);
// medium:
$dfile = "tmp/" . $filename . "_300x600." . $ext;
createTh($file,$dfile,300,600,$ext);
return true;
}

function createTh($sfile,$dfile,$maxwidth,$maxheight,$ext){
if(($ext=='jpg') OR ($ext=="jpeg")){
$simg = imagecreatefromjpeg($sfile);
}
if($ext=='png'){
$simg = imagecreatefrompng($sfile);
}
$currwidth=imagesx($simg);
$currheight=imagesy($simg);

//set the dimensions of the thumbnail
if ($currheight>$currwidth*1.7)
{
$zoom=$maxheight/$currheight;
$newheight=$maxheight;
$newwidth=$currwidth*$zoom;
}
else
{
$zoom=$maxwidth/$currwidth;
$newwidth=$maxwidth;
$newheight=$currheight*$zoom;
}
//create the resource img for the thumbnail
$dimg = imagecreate($newwidth, $newheight);
//convert truecolor immage resource to palette image resource (so we can count the colors...)
imagetruecolortopalette($simg, false, 256);
$palsize = ImageColorsTotal($simg);
for ($i = 0; $i<$palsize; $i++)
{
$colors = ImageColorsForIndex($simg, $i);
ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']);
}
imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight);
imagejpeg($dimg,$dfile);
ImageDestroy($simg);
ImageDestroy($dimg);
}
?>
[/php]

Unde este foarte clar ca:
$d = dir("img/"); este directorul in care omul are imaginile
$dfile = "tmp/" . $filename . "_100x200." . $ext; ->tmp este dirctorul in care punem imaginile rezultate

Momentan merge cu imaginii de tip jpg sau png (poti sa ai 3 jpg si 2 png ca o sa mearga)
Functia createTh() am gasit-o pe zend.com pe la sectiunea de coduri.
Folosesc functia convert($NUME_INITIAL_FISIER,$NUME_FISIER_CONVERTIT,$EXTENSIE) pentru a genera Thumbs-uri de dimensiuni diferite (100x200 si 300x600).

In cazul in care sunt multe imaginii de redimensionat, ar fi de preferat sa se adauge linia:
[php]
set_time_limit(0);
[/php]
la inceput sau sa se ruleze scriptul din linie de comanda.

taipan
Junior Member
Mesaje: 44
Membru din: Vin Sep 24, 2004 3:47 pm

Mesajde taipan » Mar Oct 19, 2004 9:48 am

Orice problema se rezolva cu o grenada.


Înapoi la “PHP Avansat”

Cine este conectat

Utilizatori ce ce navighează pe acest forum: Niciun utilizator înregistrat și 12 vizitatori