php 上傳縮放圖片

來源:互聯網
上載者:User

標籤:

有時上傳圖片時因為圖片太大了,不僅佔用空間,消耗流量,而且影響瀏(圖片的尺寸大小不一)。下面分享一種等比例不失真縮放圖片的方法,這樣,不管上傳的圖片尺有多大,都會自動壓縮到我們設定尺寸值的範圍之內。經過測試,證明實用。

view sourceprint?
01 <?php
02 function resizeImage($im,$maxwidth,$maxheight,$name,$filetype)
03  {
04   $pic_width = imagesx($im);
05   $pic_height = imagesy($im);
06   
07   if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight))
08   {
09    if($maxwidth && $pic_width>$maxwidth)
10    {
11     $widthratio = $maxwidth/$pic_width;
12     $resizewidth_tag = true;
13    }
14   
15    if($maxheight && $pic_height>$maxheight)
16    {
17     $heightratio = $maxheight/$pic_height;
18     $resizeheight_tag = true;
19    }
20   
21    if($resizewidth_tag && $resizeheight_tag)
22    {
23     if($widthratio<$heightratio)
24      $ratio = $widthratio;
25     else
26      $ratio = $heightratio;
27    }
28   
29    if($resizewidth_tag && !$resizeheight_tag)
30     $ratio = $widthratio;
31    if($resizeheight_tag && !$resizewidth_tag)
32     $ratio = $heightratio;
33   
34    $newwidth = $pic_width * $ratio;
35    $newheight = $pic_height * $ratio;
36   
37    if(function_exists("imagecopyresampled"))
38    {
39     $newim = imagecreatetruecolor($newwidth,$newheight);//PHP系統函數
40       imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);//PHP系統函數
41    }
42    else
43    {
44     $newim = imagecreate($newwidth,$newheight);
45       imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
46    }
47   
48    $name = $name.$filetype;
49    imagejpeg($newim,$name);
50    imagedestroy($newim);
51   }
52   else
53   {
54    $name = $name.$filetype;
55    imagejpeg($im,$name);
56   }
57  }
58 //使用方法:
59 $im=imagecreatefromjpeg("./20140416103023202.jpg");//參數是圖片的存方路徑
60 $maxwidth="600";//設定圖片的最大寬度
61 $maxheight="400";//設定圖片的最大高度
62 $name="123";//圖片的名稱,隨便取吧
63 $filetype=".jpg";//圖片類型
64 resizeImage($im,$maxwidth,$maxheight,$name,$filetype);//調用上面的函數

 

處理前圖片大小:1187*846

圖片處理後大小:561*400

處理後的圖片名稱:123.jpg

寫 在最後:因為客戶要求使用php實現等比例不失真縮放上傳圖片,本來要自己寫的,但百度一下發現了這個函數,於是乎就拿來用了,呵呵,省了我不少時間啊! 其實我們想到的一些新功能,網路早已有之,猶其在中國,很多的創新,其實都是從國外翻譯過來的,在代碼這方面,老外的腦子確實很好使。上面的函數,作者不 詳,但還是要感謝作者的辛苦付出。

php 上傳縮放圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.