PHPで画像のサムネイル作成

このQ&Aのポイント
  • PHPの画像処理関数を使って、大きなサイズの画像を小さなサムネイルに変換するクラスを作成しました。
  • サムネイルのサイズを変更しても表示される画像が変わらない問題が発生しました。
  • クラスの定義を調べても問題箇所が見つからず、解決方法がわかりません。お知恵を貸していただけないでしょうか?
回答を見る
  • ベストアンサー

PHPで画像のサムネイル作成

PHPの画像処理関数を使って、大きなサイズの画像を小さなサムネイルに変換するクラスを作りました。 このクラスを使ってサムネイルを表示させるクライアントプログラムを作り、実行させたのですが、うまくいきません。 下にクラスの定義と、プログラムを掲載してありますが、プログラム中のインスタンス作成文である $thumb=new ThumbNailImage($path, 100); の第2パラメータであるサイズをいくら変えても、表示される画像は元のままです。 また、この文をコメントアウトして、 //echo "thumbnail size: width= $width, height= $height</br>"; のコメントを外し実行すると、画像サイズは表示されず、 thumbnail size: width=, height= とだけ表示されます。 これらのことから、クラスの定義がおかしいのだろうと思って、各関数をくまなく調べたのですが、どこがおかしいのかわかりません。 どなたかお知恵を貸していただけないでしょうか。 どうぞよろしくお願いいたします。 クライアントプログラム: <?php require 'ThumbNailImage.php'; $path="samples"; $file="p2230331.jpg"; $path=realpath("$path/$file"); $thumb=new ThumbNailImage($path, 100); $thumb->getImage();// including header in this function $width= $thumb->getThumbWidth(); $height= $thumb->getThumbHeight(); //echo "thumbnail size: width= $width, height= $height</br>"; ?> クラス定義: 長すぎて質問欄に入りきらないかもしれないので、不要と思われる関数は除いてあります。 <?php class ThumbNailImage{ private $image; private $quality=100; private $mimetype; private $imageproperties = array(); private $initialfilesize; private $thumbwidth; private $thumbheight; public function __construct($file, $thumbnailsize) { is_file($file) or die("file $file does not exist"); $this->initialfilesize = filesize($file);// file size in bytes $this->imageproperties = getimagesize($file); // $imageproperties[0]= width // $imageproperties[1]= height // $imageproperties[2]= mime type constant $this->mimetype = image_type_to_mime_type($this->imageproperties[2]); // create image switch($this->imageproperties[2]){ case IMAGETYPE_JPEG: $this->image=imagecreatefromJPEG($file); break; case IMAGETYPE_GIF: $this->image=imagecreatefroGIF($file); break; case IMAGETYPE_PNG: $this->image=imagecreatefromPNG($file); break; default: die("could not create image"); } // end case $this->createThumb($thumbnailsize); } public function createThumb($thumbnailsize) { $srcW=$imageproperties[0]; $srcH=$imageproperties[1]; $prop=array(); if($srcW > $thumbnailsize || $srcH > $thumbnailsize){ $reduction = $this->calculateReduction($thumbnailsize); $destW=round($srcW/$reduction); $destH=round($srcH/$reduction); $copy = imagecreatetruecolor($destW, $destH); imagecopyresized($copy, $this->image, 0,0,0,0,$destW, $destH, $srcW, $srcH); imagedestroy($this->image); $this->image = $copy;// now $this->image has the thumbnail image $prop=getimagesize($this->image); $this->thumbwidth=$prop[0]; $this->thumbheight=$prop[1]; } }// end function public function calculateReduction($thumbnailsize) { $srcW=$imageproperties[0]; $srcH=$imageproperties[1]; if($srcH > $srcW){ $reduction = round($srcH/$thumbnailsize); }else{ $reduction = round($srcW/$thumbnailsize); } return $reduction; } public function getImage() { header("content-type: $this->mimetype"); switch($this->imageproperties[2]){ case IMAGETYPE_JPEG: imagejpeg($this->image,NULL,$this->quality); break; case IMAGETYPE_GIF: imagegif($this->image,NULL ); break; case IMAGETYPE_PNG: imagepng($this->image,NULL, $this->quality); break; default: die("could not create image"); } // end case ; } if($this->imageproperties[2]==IMAGETYPE_JPEG || $this->imageproperties[2]==IMAGETYPE_PNG){ if($quality >100 || $quality < 1){ $this->quality = 75; // default in case of wrong parameter }else{ $this->quality=$quality; } } } public function getThumbWidth() { return $this->thumbwidth; } public function getThumbHeight() { return $this->thumbheight; } }// end class ?>

  • PHP
  • 回答数2
  • ありがとう数2

質問者が選んだベストアンサー

  • ベストアンサー
回答No.2

すまそ! XAMPPだと、ImageMagickが入ってないわ。。 無理やり使えるようにしたいなら、これ。 https://qiita.com/qiita_mona/items/c340e6d0417139a9b148 標準の関数(GDライブラリ)だけで、リサイズをするなら、 https://www.php.net/manual/ja/function.imagecopyresized.php $newwidth = $width * $percent; $newheight = $height * $percent; ここに、新しい側のサイズが入るようにして実行で OKじゃないかな。。 ↑これだと、全体的なサイズになるけど、 サムネイルの場合は、 先に、WとHの「長いほう」を基準に 「短いほう」を割り算する感じね。 /* 元のサイズ */ $w=1000; $h=1000; /* 縮小後のサイズ */ $out_w=320; $out_h=240; /* 比率計算 */ $wp=$w/$out_w; $hp=$h/$out_h; echo "W=".($out_w)." H=".($h/$wp); if ($wp>=$hp) echo "こっち"; echo "<br>"; echo "W=".($w/$hp)." H=".($out_h); if ($wp<$hp) echo "こっち"; echo "<br>"; そんで、求まった比率を今回の画素の中心に配置すればOK ようするに・・・ 320x240 というサムネイルサイズに、縮小後 320x200のサイズだとして。。 $center_x=($thm_w-$img_w)/2; $center_y=($thm_h-$img_h)/2; 320-320=0それを2で割って0 240-200=40それを2で割って20 つまり、左上の位置は(0,20)ってこと すべての画像が、真四角とは限らないし、 サムネイルにしたサイズが四角とも限らないから、 比率で求めれば、思った結果に一番近いんじゃないかなとは 思う。。 結局「サムネイルを作る」のと「リサイズする」のは 同じことだから、結果的に正しい結果が得られたら それでいいんじゃないかな~と。 これでどう?

papashiroSooke
質問者

お礼

有難うございます。一応教えて頂いたようにしてやってみます。 また、ひとつ考えたのですが、AsarKingChang さんのおっしゃる通り、結局「サムネイルを作る」のと「リサイズする」のは同じことだから、HTMLの<img>タグを使ってwidth=100 とかにしたらそれでいいような気もします。 多数画像が入ったフォルダーをreaddir()で一つずつ読みだして、 echo "<img src=\"$file_name\" width=100 ><br/>"; のような形です。 いずれにしても、今回はこれで締め切りにさせて頂きたいと思います。 色々教えて頂き、本当に有難うございます。

その他の回答 (1)

回答No.1

なんか、見覚えがあるぞぉ~(w) そんで、やりたいことそのままが、すでにサンプルにあるんだわ。 https://www.php.net/manual/ja/imagick.thumbnailimage.php って感じで、やってみて

papashiroSooke
質問者

お礼

早速にご回答を頂きまして、有難うございます。 前回の私の質問にも答えて頂いた AsarKingChang さんですよね。またお世話になります。 教えて頂いたサイトのサンプルをコピーしてきてみたのですが、 imagick というクラスを何処からインクルードすればよいのかわかりません。 それに、私はまだphpの学習者なので、今実際に大きな画像のサムネイルを作る必要性があるわけではありません。クラス作成の練習としてこれを作ったのですが、それがうまく働かないので、どこにミスがあるのかを知りたいのです。そういう意味で、もしお時間があればで良いのですが、わたしのくらすていぎをみていただけないでしょうか。 宜しくお願いいたします。

関連するQ&A

  • PHPの画像処理

    PHP学習者です。 画像ディレクトリー内の画像をサイズを変えて表示するプログラムを作りましたが、JPG形式は表示されてもPNG形式やGIFが表示されません。 関係すると思われるコードの一部を掲載します。コードがおかしいのか、あるいは何かPNGのためにはしておくことがあるのか、詳しい方どうか教えてください。お願いします。 //*************************************************** public function getImage() // create thumbnail image to be sent to browser //*************************************************** { header("content-type:$this->mimetype"); switch($this->imageproperties[2]){ case IMAGETYPE_JPEG: imagejpeg($this->image,"",$this->quality); break; case IMAGETYPE_GIF: imagegif($this->image,""); break; case IMAGETYPE_PNG: imagepng($this->image,"", $this->quality); break; default: die("could not create image"); } // end case ; }

    • ベストアンサー
    • PHP
  • [PHP]GDを利用した画像リサイズについて

    [PHP]GDを利用した画像リサイズについて GDを利用した画像リサイズ処理を行うクラスを作ったのですが、 以下のようなエラー(文字化け)が出てしまい画像出力することができません。 有識者の方、どうか知恵をお貸しください。宜しくお願い致します。 ????JFIF??;CREATOR: gd-jpeg v1.0 (using IJG JPEG v70), quality = 75 ??C    $.' ",#(7),01444'9=82<.342??C  2!!22222222222222222222222222222222222222222222222222??II"?? ???}!1AQa"q2???#B??R??$3br? %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz??????????????????????????????????????????????????????????????????????????? ???w!1AQaq"2?B???? #3R?br? -------- 以下省略 ---------- ◆作成したPHPファイル ・test.php <?php require_once 'Image.php'; $path = './400x300.jpg'; $r = new Image($path, 75); $r->resize(75); ?> ・Images.php <?php class Image{ var $new_width; var $path; function Image($path, $new_width){ @header("Content-type: image/jpeg"); $this->path = $path; $this->new_width = $new_width; } function resize(){ global $new_width; global $path; // 画像パス $image = imagecreatefromjpeg($this->path); // 画像のサイズを取得 $width = 150; $height = 150; $rate = $this->new_width / $width; $new_height = $rate * $height; $thumb = imagecreatetruecolor($this->new_width, $new_height); imagecopyresized($thumb, $image, 0, 0, 0, 0, $this->new_width, $new_height, $width, $height); // imagecopyresampled($thumb, $image_path, 0, 0, 0, 0, $this->new_width, $new_height, $width, $height); imagejpeg($thumb, null, 75); imagedestroy($image); } } ?> ◆環境と状況 ・サーバ:WindowsXP(XAMPPを利用してローカル環境を構築) ・phpinfo()にて、GD Support=enabled、JPEG Support=enabledを確認 ・ステップ実行(デバック)にてimagejpeg($thumb, null, 75);まで問題なく実行可能。  ※imagejpeg($thumb, null, 75);実行後上記文字列が出力される。 ・コメントアウト個所のimagecopyresampledでも動作結果は同じ。 ・参考にしたサイト  http://goodjob.boy.jp/chirashinoura/id/79.html 恐れ入りますが、ご回答お願い致します。

    • ベストアンサー
    • PHP
  • 【jQuery】サムネイル

    3つのサムネイル画像(.thumb)があります。 クリックした.thumbはopacityを1に、その他は0.5に切り替わる する方法を教えてください。 始めは1番目.thumbのopacityは1でお願いします。 ■html <div id="ph-wrap"> <div id="photo"> <p><img src="./img/photo1.png" width="480" height="320" alt="" /></p> <p><img src="./img/photo2.png" width="480" height="320" alt="" /></p> <p><img src="./img/photo3.png" width="480" height="320" alt="" /></p> </div> <div id="thumb-wrap"> <p class="thumb"><img src="./img/photo1.png" width="120" height="80" alt="" /></p> <p class="thumb"><img src="./img/photo2.png" width="120" height="80" alt="" /></p> <p class="thumb"><img src="./img/photo3.png" width="120" height="80" alt="" /></p> </div> </div> ■CSS(一部抜粋) #thumb-wrap{ float:left; margin:0 0 0 10px; padding:0; width:120px; } #thumb-wrap img{ width:120px; height:80px; cursor:pointer; opacity:0.5; -moz-opacity:0.5; /* Firefox */ filter: alpha(opacity=50); /* IE */ } .opc{ opacity:1.0; -moz-opacity:1; /* Firefox */ filter: alpha(opacity=100); /* IE */ } ■jQuery $(function () { var photoImg = "#photo img" var thumbWrapImg = "#thumb-wrap img" $("#photo p:gt(0)").hide(); $(thumbWrapImg).eq(0).css({"opacity":1}); $(thumbWrapImg).click(function () { $(this).animate({"opacity":1},100); $(photoImg).attr("src",$(this).attr("src")); }); });

  • サムネイル画像が表示されない

    以前質問しましたがもう一度お願いします。 HPビルダー7 でサムネイル画像の大きい画像がネット上で表示されません。(プレビューでは表示されます。)ISPのぷららに聞くとアップロードされてないらしいのですが、ソフトの問題なのでそれ以上答えてくれません。ちなみに、HTMLソースは <TD align="center" valign="middle" width="128" height="128"><A href="IMG_0597.JPG"><IMG src="IMG_0597_thumb.JPG" width="128" height="96" border="1"></A></TD> です。なぜ、小さい画像をクリックしても大きい画像が表示されないか分かりません。なにかヒントでもいいですからお願いします。

  • javascriptを使い、サムネイル表示

    サンプルHP⇒http://cartown.jp/detail_dt.php?car_id=1990056 のような、サムネイル画像と拡大画像を表示させる記述方法を 教えてください。 下記のような回答文を確認したのですが、img要素を列挙する記述やonclickイベントを結びつける記述すらわかりません。こんな超初心者ですが、よろしくお願い致します。 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ <html> <head> <meta http-equiv="Content-Language" content="ja"> <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS"> <meta http-equiv="Content-Style-Type" content="text/css"> <meta http-equiv="Content-Script-Type" content="text/javascript"> <title>サンプル</title> <script type="text/javascript"> function showImg(){ document.getElementById("image").src=this.src; } function setup(){ var thumbnails=document.getElementsByName("thumbnail");//name="thumbnail"とついているimg要素を列挙 for(var i=0;i<thumbnails.length;i++)thumbnails[i].onclick=showImg;//↑で列挙したものにonclickイベントを結びつける } window.onload=setup; </script> <style type="text/css"> .main td{ width:300px; height:300px; } </style> </head> <body> <table border class="main"> <tr> <td><img id="image" width="300" height="300"></td> <td> 文章 </td> </tr> </table> <!--ここから下の画像はサムネイル用ではなく、上に表示する予定の画像と同じもので width属性とheight属性を指定して大きさを変えています。(ここでは全部300x300の画像とします。)--> <table border> <tr> <td><img name="thumbnail" src="img1.png" width="48" height="48"></td> <td><img name="thumbnail" src="img2.png" width="48" height="48"></td> <td><img name="thumbnail" src="img3.png" width="48" height="48"></td> <td><img name="thumbnail" src="img4.png" width="48" height="48"></td> <td><img name="thumbnail" src="img5.png" width="48" height="48"></td> </tr> <tr> <td><img name="thumbnail" src="img6.png" width="48" height="48"></td> <td><img name="thumbnail" src="img7.png" width="48" height="48"></td> <td><img name="thumbnail" src="img8.png" width="48" height="48"></td> <td><img name="thumbnail" src="img9.png" width="48" height="48"></td> <td><img name="thumbnail" src="img10.png" width="48" height="48"></td> </tr> </table> サムネイルクリックで拡大します。 </body> </html>

  • 画面移遷なしで画像アップロード&サムネイル表示

    画像をアップロードするフォームで、 アップロードする画像を選択→画面移遷なしでアップロード→サムネイルを動的表示 というようにしたいのですが、うまくいきません。 以下のjQueryプラグインが希望の動作に近そうなのですが、詳しい設置方法がわかりません。 http://www.ideaxidea.com/archives/2010/03/ajax_upload.html とりあえず、サンプルにならって、jQueryとajaxupload.jsを読み込んで、以下のように設置してみましたがサムネイルが表示されません。 アドバイスをいただけると助かります。 ヘッダーに↓ <script type="text/javascript"> $(document).ready(function(){ var thumb = $('img#thumb'); new AjaxUpload('imageUpload', { action: $('form#newHotnessForm').attr('action'), name: 'image', onSubmit: function(file, extension) { $('div.preview').addClass('loading'); }, onComplete: function(file, response) { thumb.load(function(){ $('div.preview').removeClass('loading'); thumb.unbind(); }); thumb.attr('src', response); } }); }); </script> bodyに↓ <h2>New Hotness</h2> <div class="column-row"> <div class="seven columns"> <div class="preview"> <img id="thumb" width="100px" height="100px" src="/img/hoge.png" /> </div> <span class="wrap hotness"> <form id="newHotnessForm" action="/post.php"> <label>Upload a Picture of Yourself</label> <input type="file" id="imageUpload" size="20" /> <button type="submit" class="button">Save</button> </form> </span> </div> </div>

    • ベストアンサー
    • AJAX
  • upload.php内のページ転送について

    header Locationの転送について教えてください。 PHPファイル内で画像プレビューを表示させ ページ転送を行いたいです。 しかし、プレビューが表示される部分に 転送先の<header>(html5)の内容が表示されてしまいます。 どこが悪くてどう直せば良いのでしょうか? どなたか教えてください。 <?php header("Location: http://www.********.com/"); ?> <?php //前にアップロードされた写真のファイル名 $postPhotoName = $_POST["postPhotoName"]; $result = false; if($_FILES['img']['name'] == "") { die("ファイルがないぜよ。"); }else{ //アップロードされたファイルの情報を取得 $fileName = basename(date("U")."-".$_FILES['img']['name']); $fileType = $_FILES['img']['type']; $fileTmpName = $_FILES['img']['tmp_name']; if(!preg_match("/jpeg/",$fileType)){ unlink($fileTmpName); die( "jpegじゃないぜよ。"); }else{ //ファイルの保存 if (!move_uploaded_file($fileTmpName, 'thumbimg/' . $fileName)) { die('保存にしっぱいしたぜよ。'); } else { //サムネイル作成 include('class.image.php'); list($width, $height, $type, $attr) = getimagesize('thumbimg/'.$fileName); $thumb = new Image('thumbimg/'.$fileName); $thumb->name('thumb-'.basename($fileName,".jpg")); if($width>$height){ if($width > 380) $thumb->width(380); }else{ if($height > 400) $thumb->height(400); } $thumb->save(); $result = true; } } } if($result == true){ ?> <img src="<?php echo 'thumbimg/thumb-'.$fileName;?>"> <input type="hidden" value="<?php echo $fileName?>" name="postPhotoName" id="postPhotoName"> <?php }

    • 締切済み
    • PHP
  • JavaScriptの画像入れ替えについて

    下記のようなものでサムネイルをクリックすると大きな画面に表示される、みたいなものを作っています。しかし職場のIE6でクリックすると表示されなく大きな画像が消えてしまいます。 ちなみに自宅のIE6で確認したときは大丈夫だったのですが、、、 またサムネイル画像のアンカー部分のjavasscript:void(0);を消すと表示されるようになるのですが、やはりここのvoid0には問題があるのでしょうか?? またサーバーにUPする前オンライン上ではなくPCで確認している時はちゃんと表示できていたました。 あまり詳しくないものでどなたかよろしくお願い致します。 <script type="text/javascript"> <!-- function imgch(url) { document.getElementById("image").src=url; } //--> </script> <style type="text/css"> img { border:none; } </style> </head> <body> <img src="image/2.jpg" width="500" height="500" id="image" /> <a href="javascript:void(0);"><img src="image/2.jpg" width="50" height="50" onClick="imgch(this.src)" ></a> <a href="javascript:void(0);"><img src="image/3.jpg" width="50" height="50" onClick="imgch(this.src)" ></a> <a href="javascript:void(0);"><img src="image/3.jpg" width="50" height="50" onClick="imgch(this.src)" ></a> </body>

  • MT4のファイルオプション画面のカスタマイズ

    MT4のファイルオプション画面のカスタマイズについて質問です。 画像をアップロードする際にデフォルトでサムネイルの幅を固定することができたのですが、その設定をブログのIDごとに分岐したいのです。 イメージとしては、 【mt/tmpl/cms/dialog/asset_options_image.tmpl 内】---------------- <mt:if ブログのID="1"> <mt:if name="do_thumb"> <mtapp:setting id="create_thumbnail" label="<__trans phrase="Use thumbnail">" label_class="no-header" hint="" show_hint="0" help_page="file_upload" help_section="creating_thumbnails"> <input type="checkbox" name="thumb" value="1" checked="checked" /> <label for="create_thumbnail"><__trans phrase="Use thumbnail"></label> (<label for="thumb_width"><__trans phrase="width:"></label> <input name="thumb_width" id="thumb_width" value="200" disabled onkeypress="widthKeyPress(event)" onchange="adjustWidthHeight(this.form, 1)" size="4" /> <__trans phrase="pixels">) <input type="hidden" name="thumb_height" value="<mt:var name="thumb_height">" /> <img onload="checkThumbs('now');" src="<mt:var name="static_uri">images/spacer.gif" alt="" width="1" height="1" /> </mtapp:setting> </mt:if> </mt:if> <mt:if ブログのID="2"> <mt:if name="do_thumb"> <mtapp:setting id="create_thumbnail" label="<__trans phrase="Use thumbnail">" label_class="no-header" hint="" show_hint="0" help_page="file_upload" help_section="creating_thumbnails"> <input type="checkbox" name="thumb" value="1" checked="checked" /> <label for="create_thumbnail"><__trans phrase="Use thumbnail"></label> (<label for="thumb_width"><__trans phrase="width:"></label> <input name="thumb_width" id="thumb_width" value="400" disabled onkeypress="widthKeyPress(event)" onchange="adjustWidthHeight(this.form, 1)" size="4" /> <__trans phrase="pixels">) <input type="hidden" name="thumb_height" value="<mt:var name="thumb_height">" /> <img onload="checkThumbs('now');" src="<mt:var name="static_uri">images/spacer.gif" alt="" width="1" height="1" /> </mtapp:setting> </mt:if> </mt:if> -------------------------------------------------------------------- のような感じで、ブログ1にはサムネイルの幅200、ブログ2にはサムネイルの幅400と分岐して指定したいのです。 tmplファイルでのブログID条件分岐がどうしても分らなかったので質問させていただきました。 是非御回答よろしくお願いします!

    • 締切済み
    • PHP
  • PHPの読解お願いいたします クラスについて

    独学でPHPを学んでます。 環境:XAMPPにて1.7.0でアパッチなど一括ダウンロード クラスについておおまかな概念は分かりますが、細かな点が多々わかりません。 下記コードをまずご覧ください。 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <html> <head> <title> </title> </head> <body> <?php $test=new Figure(3,4); print "三角形の面積は"; print $test->getarea();● print "となります"; class Figure{ protected $width; △ protected $height;△ function __construct($width,$height){ $this->width=$width; $this->height=$height; } function getarea(){ return $this->width * $this->height;●● } } </table> </body> </html> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ まず私の解釈ですが、 コンストラクターでオブジェクトが作成される $width $heightにそれぞれ、3と4が格納。 クラス内ではメンバ変数を$thisであらわす必要性があることから、$widthと$heightをそれぞれ$this->width $this->heightにする。 ●で$test->getarea()を呼んでいるので●●の部分の計算が行われ、その値を再度$test->getarea()に返す。 以上になりますが、なぜかエラーが出ます。 どこに誤りがありますでしょうか。 また●の部分 $test->getarea()ですが、これは関数呼び出し文とはまた別のものなのでしょうか。もし関数呼び出し文であるなら、print表記は必要ないとは思うのです。また関数呼び出し文は文字列ではないので、""は必要はないとの理解でよろしいでしょうか。 さらに△の二行につき、このコード上での存在意義とはなんでしょうか。 以上、よろしくお願いいたします。

    • ベストアンサー
    • PHP