31
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP GDで画像を自動で縮小してアップする

Posted at

PHP で画像を自動で縮小してアップする方法をメモします。

やりたいこと

  • 画像を1枚アップする
  • JPG画像のみアップできる
  • 指定サイズ以上の画像のみアップできる
  • 指定サイズより大きい場合は指定サイズに自動で縮小
  • 縮小する際は幅・高さの長いほうを指定サイズに合わせる

ソース

example.tml
<form action="example.php" method="post" name="FormName" enctype="multipart/form-data">
<input type="file" name="up_img" value="参照" class="example">
<input type="submit" name="submit" value="送信">
</form>
example.php
if ($_POST['submit']) {
	if (is_uploaded_file($_FILES["up_img"]["tmp_name"])) {
		$file1 = $_FILES["up_img"]["tmp_name"]; // 元画像ファイル
		$file2 = "../img/example.jpg"; // 画像保存先のパス
		$in = ImageCreateFromJPEG($file1); // 元画像ファイル読み込み
		$width = ImageSx($in); // 画像の幅を取得
		$height = ImageSy($in); // 画像の高さを取得
		$min_width = 500; // 幅の最低サイズ
		$min_height = 500; // 高さの最低サイズ
		$image_type = exif_imagetype($file1); // 画像タイプ判定用

		if ($image_type == IMAGETYPE_JPEG){ // JPGかどうか判定
			if($width >= $min_width|$height >= $min_height){
				if($width == $height) {
					$new_width = $min_width;
					$new_height = $min_height;
				} else if($width > $height) {//横長の場合
					$new_width = $min_width;
					$new_height = $height*($min_width/$width);
				} else if($width < $height) {//縦長の場合
					$new_width = $width*($min_height/$height);
					$new_height = $min_height;
				}
				// 画像生成
				$out = ImageCreateTrueColor($new_width , $new_height);
				ImageCopyResampled($out, $in,0,0,0,0, $new_width, $new_height, $width, $height);
				ImageJPEG($out, $file2);
			} else {
				echo "サイズが幅".$min_width."×高さ".$min_height."以上の画像をご用意ください";
			}
		} else {
			echo "JPG画像をご用意ください";
		}
}
31
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?