画像をリサイズ

function createThumbs( $imagePath) {
    // 画像の情報を取得
    $size = getimagesize( $path . $actual_image_name);

    // JPEG
    if ($size['mime'] == 'image/jpeg') {
        $image = imagecreatefromjpeg( $path . $actual_image_name );
    } else 
    // PNG
    if ($size['mime'] == 'image/png') {
        $image = imagecreatefrompng(  $path . $actual_image_name);
    } else 
    // GIF
    if ($size['mime'] == 'image/gif') {
        $image = imagecreatefromgif(  $path . $actual_image_name);
    }

    $width  = imagesx( $image );
    $height = imagesy( $image );
    if ($width >= $height ) {
        // 横長の画像の時
        $side = $height;
        $x = floor( ( $width - $height) / 2);
        $y = 0;
        $width = $side;
    } else {
        // 縦長の画像の時
        $side = $width;
        $y = floor( ( $height - $width) / 2);
        $x = 0;
        $height = $side;
    }

    $thumbnail_width  = 150;
    $thumbnail_height = 150;
    $thumbnail = imagecreatetruecolor( $thumbnail_width, $thumbnail_height );

    // PNG
    if ($size['mime'] == 'image/png') {
        imagealphablending( $thumbnail, false);      // アルファブレンディングをoffにする
        imagesavealpha( $thumbnail, true);           // 完全なアルファチャネル情報を保存するフラグをonにする
    } else 
    //    GIF
    if ($size['mime'] == 'image/gif') {
        $alpha = imagecolortransparent( $image);     // 元画像から透過色を取得する
        imagefill( $thumbnail, 0, 0, $alpha);        // その色でキャンバスを塗りつぶす
        imagecolortransparent( $thumbnail, $alpha);  // 塗りつぶした色を透過色として指定する
    }

    imagecopyresampled( $thumbnail, $image, 0, 0, $x, $y, $thumbnail_width, $thumbnail_height, $width, $height);

    // JPEG
    if ($size['mime'] == 'image/jpeg') {
        imagejpeg( $thumbnail, $path . $actual_image_name . '_thumb' );
    } else 
    // PNG
    if ($size['mime'] == 'image/png') {
        imagepng( $thumbnail, $path . $actual_image_name . '_thumb' );
    } else 
    //    GIF
    if ($size['mime'] == 'image/gif') {
        imagegif( $thumbnail, $path . $actual_image_name . '_thumb' );
    }

}

画像の形式を取得する

$size = getimagesize( 'ファイルパス');
//  $sizeデバッグ
Array
(
    [0] => 599                       // 画像の幅
    [1] => 450                       // 画像の高さ
    [2] => 3                         // 
    [3] => width="599" height="450"  // 
    [bits] => 8                      // 
    [mime] => image/png              // MIMEタイプ
)

  • このエントリーをはてなブックマークに追加

関連記事

no image

Composer インストール

# curl -sS https://getcomposer.org/installer | php # mv composer.phar /usr/local/bin/composer

no image

時刻系関数

PHP ミリ秒/マイクロ秒 現在時刻をミリ(マイクロ)秒まで表示やログ出力する。microtime()を使用します。 list( $microSec, $timeStamp) = expl

no image

文字列操作

パディング str_pad 対象文字列に対して、特定の文字でパディング(埋める)を行います。 str_pad ( 対象文字列, パディング後の文字数, パディングの文字, パディングの方向) st

Message

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

*

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください

    PAGE TOP ↑