2013-05-08 96 views
1

我想为每个项目上传多个图像。图像上传成功,但需要很长时间才能加载这些图像。所以,我想将上传的图像保存为jpeg,以便它可以轻松加载。保存所有图像为jpeg在php

+0

检查http://php.net/manual/en/function.imagejpeg.php – 2013-05-08 04:19:13

回答

1

使用PHP库,用于图像GD2或使用SimpleImage PHP类

$src='uploads/'.$_REQUEST['name']; 
$newsrc='profiles/'.$_REQUEST['name']; 
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{ 
    $targ_w=$_POST['w']; 
    $targ_h=$_POST['h']; 


    $jpeg_quality = 90; 
    $img_r = imagecreatefromjpeg($src);//you can chose other option like imagecreatetruecolor($_POST['w'],$_POST['h']) etc 
    $dst_r = ImageCreateTrueColor($_POST['w'],$_POST['h']); 

    imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],$targ_w,$targ_h,$_POST['w'],$_POST['h']); 

    imagejpeg($dst_r,$newsrc,$jpeg_quality) or die("Unable to save image"); 

    imagedestroy($img_r); 


} 
0

您可以使用下面的代码上传图片,将压缩你的形象,你也可以用正常的修改将其转换到JPG。

<?php 
/* 
Template Name: image compress 
*/ 
if(isset($_POST['submit'])){ 

//print each file name 
//echo count($_FILES['new_image']['name']); 
for($i=0; $i<count($_FILES['new_image']['name']); $i++) 
{  
      $imagename = $_FILES['new_image']['name'][$i]; 
      $source = $_FILES['new_image']['tmp_name'][$i]; 
      $a=$_SERVER['DOCUMENT_ROOT']; 
      $target = "full/path/where/you/save /image/".$imagename; 
      move_uploaded_file($source, $target); 

      $imagepath = $imagename; 
      //$imagename = explode('.',$imagepath); 
      $save = "full/path/where/you/save /image/". $imagepath; //This is the new file you saving 
      $file = "full/path/where/you/save /image/". $imagepath; //This is the original file 

      list($width, $height) = getimagesize($file) ; 


      $tn = imagecreatetruecolor($width, $height) ; 
      $image = imagecreatefromjpeg($file) ; 
      imagecopyresampled($tn, $image, 0, 0, 0, 0, $width, $height, $width, $height) ; 
      //.image_type_to_extension(IMAGETYPE_JPEG) image file convert 
      imagejpeg($tn, $save,50) ; 

      $thumb = imagecreatetruecolor($newwidth, $newheight); 

      /*$save = $a."/demo/mainn/". $imagepath; //This is the new file you saving 
      $file = "full/path/where/you/save /image/". $imagepath; //This is the original file 

      list($width, $height) = getimagesize($file) ; 

      $modwidth = 176; 

      $diff = $width/$modwidth; 

      $modheight = 255; 
      $tn = imagecreatetruecolor($modwidth, $modheight) ; 
      $image = imagecreatefromjpeg($file) ; 
      imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; 

      imagejpeg($tn, $save, 80); */ 
     } 
    } 
    ?> 
    <form action="<?php ?>" method="post" enctype="multipart/form-data" id="something" class="uniForm"> 
    <!--<input name="new_image" id="new_image" size="30" type="file" class="fileUpload" />--> 
    <input name="new_image[]" type="file" multiple="multiple" /> 
    <button name="submit" type="submit" class="submitButton">Upload/Resize Image</button> 
    </form> 

把这个放在你的服务器上,而不是上传图像时它会压缩20%,当它加载的时候花费的时间不多。