multi image upload

Статус
В этой теме нельзя размещать новые ответы.

lashka1

Постоялец
Регистрация
31 Авг 2007
Сообщения
59
Реакции
6
привет.
у меня ест вот такои класс для загризки фото помагите пожалуста переделат так што одновременно загружалос 6 фото
PHP:
 <input type="file" name="image" class="file"/>
PHP:
<?php
class Image{	
	// uploading graphic
	function upload($i, $mWidth, $mHeight, $sWidth, $sHeight, $bg, $Quality, $bigThumb, $smallThumb){
		// main variables
		global $mainframe;
		$randomHash = rand(100000, 999999);
		// Checking format - JPG/PNG/GIF are allowed
		if( $_FILES['image'.$i]['type'] == 'image/pjpeg' || 
			$_FILES['image'.$i]['type'] == 'image/jpg' || 
			$_FILES['image'.$i]['type'] == 'image/jpeg' || 
			$_FILES['image'.$i]['type'] == 'image/png' || 
			$_FILES['image'.$i]['type'] == 'image/gif' ||
			$_FILES['image'.$i]['type'] == 'image/x-png' )
		{
			// Removing from name all problematic chars
			$new_name = '.jpg';
			// importing filesystem library
			// trying to upload file
			//places files into same dir as form resides
			//places files into same dir as form resides
				 move_uploaded_file($_FILES['image'.$i]['tmp_name'], './posters/'.$randomHash.'.jpg');  
		}
		// when everything is ok - we create thumbnails
		// big thumbnail
		if($bigThumb){
			$this->createThumbnail('./posters/'.$randomHash.$new_name, $randomHash.$new_name,$mWidth,$mHeight,'s_big',false,$bg,'./posters/', $Quality);
		}
		// small thumbnail
		if($smallThumb){
			$this->createThumbnail('./posters/'.$randomHash.$new_name, $randomHash.$new_name,$sWidth,$sHeight,'s_small',false,$bg,'./posters/', $Quality, true);
		}
		// returning filename
		return $randomHash.$new_name;
	}
	/*
		Creating thumbnails
	*/
	function createThumbnail($path, $name, $baseWidth, $baseHeight, $size, $str, $bg, $pathB, $Quality, $del = false){
		//script configuration - increase memory limit to 64MB
		ini_set('memory_limit', '64M');
		// Duplicate path
		$imageToChange = $path;
		// Stretching
		$stretch = ($str == false && isset($_POST['stretch'])) ? $_POST['stretch'] : (($str == 1 || $str == true) ? true : false); 
		// Getting informations about image
		$imageData = getimagesize($path);
		// Creating blank canvas
		$imageBG = imagecreatetruecolor($baseWidth, $baseHeight);
		// If image is JPG or GIF
		if($imageData['mime'] == 'image/jpeg' || $imageData['mime'] == 'image/pjpeg' || $imageData['mime'] == 'image/jpg' || $imageData['mime'] == 'image/gif') 
		{
			// when bg is set to transparent - use black background
			if($bg == 'transparent')
			{
				$bgColorR = 0;
				$bgColorG = 0;
				$bgColorB = 0;				
			} 
			else // in other situation - translate hex to RGB
			{
				if(strlen($bg) == 4) $bg = $bg[0].$bg[1].$bg[1].$bg[2].$bg[2].$bg[3].$bg[3];
				$hex_color = strtolower(trim($bg,'#;&Hh'));
	  			$bg = array_map('hexdec',explode('.',wordwrap($hex_color, ceil(strlen($hex_color)/3),'.',1)));
				$bgColorR = $bg[0];
				$bgColorG = $bg[1];
				$bgColorB = $bg[2];
			}
			// Creating color
			$rgb = imagecolorallocate($imageBG, $bgColorR, $bgColorG, $bgColorB);
			// filling canvas with new color
			imagefill($imageBG, 0, 0, $rgb);	
		}
		else // for PNG images
		{	
			// enable transparent background 
			if($bg == 'transparent')
			{
				// create transparent color
				$rgb = imagecolorallocatealpha($imageBG, 0, 0, 0, 127);
			}
			else // create normal color
			{
				// translate hex to RGB
				$hex_color = strtolower(trim($bg,'#;&Hh'));
	  			$bg = array_map('hexdec',explode('.',wordwrap($hex_color, ceil(strlen($hex_color)/3),'.',1)));
				$bgColorR = $bg[0];
				$bgColorG = $bg[1];
				$bgColorB = $bg[2];				
				// creating color
				$rgb = imagecolorallocate($imageBG, $bgColorR, $bgColorG, $bgColorB);
			}
			// filling the canvas
			imagefill($imageBG, 0, 0, $rgb);
			// enabling transparent settings for better quality
			imagealphablending($imageBG, false);
			imagesavealpha($imageBG, true);
		}
		// loading image depends from type of image		
		if($imageData['mime'] == 'image/jpeg' || $imageData['mime'] == 'image/pjpeg' || $imageData['mime'] == 'image/jpg') $imageSource = @imagecreatefromjpeg($path);
		elseif($imageData['mime'] == 'image/gif') $imageSource = @imagecreatefromgif($path);
		else $imageSource = @imagecreatefrompng($path); 
		// here can be exist an error when image is to big - then class return blank page	
		// setting image size in variables
		$imageSourceWidth = imagesx($imageSource);
		$imageSourceHeight = imagesy($imageSource);
		// when stretching is disabled		
		if(!$stretch){
			// calculate ratio for first scaling
			$ratio = ($imageSourceWidth > $imageSourceHeight) ? $baseWidth/$imageSourceWidth : $baseHeight/$imageSourceHeight;
			// calculate new image size
			$imageSourceNWidth = $imageSourceWidth * $ratio;
			$imageSourceNHeight = $imageSourceHeight * $ratio;
			// calculate ratio for second scaling
			if($baseWidth > $baseHeight){					
				if($imageSourceNHeight > $baseHeight){
					$ratio2 = $baseHeight / $imageSourceNHeight;
					$imageSourceNHeight *= $ratio2;
					$imageSourceNWidth *= $ratio2;
				}
			}else{
				if($imageSourceNWidth > $baseWidth){
					$ratio2 = $baseWidth / $imageSourceNWidth;
					$imageSourceNHeight *= $ratio2;
					$imageSourceNWidth *= $ratio2;
				}
			}
			// setting position of putting thumbnail on canvas
			$base_x = floor(($baseWidth - $imageSourceNWidth) / 2);
			$base_y = floor(($baseHeight - $imageSourceNHeight) / 2);
		}
		else{ // when stretching is disabled
			$imageSourceNWidth = $baseWidth;
			$imageSourceNHeight = $baseHeight;
			$base_x = 0;
			$base_y = 0;
		}
		// copy image	
		imagecopyresampled($imageBG, $imageSource, $base_x, $base_y, 0, 0, $imageSourceNWidth, $imageSourceNHeight, $imageSourceWidth, $imageSourceHeight);
		// save image depends from MIME type	
		if($imageData['mime'] == 'image/jpeg' || $imageData['mime'] == 'image/pjpeg' || $imageData['mime'] == 'image/jpg')
		 imagejpeg($imageBG,$pathB.'thumb'.$size.'_'.$name, $Quality);
		elseif($imageData['mime'] == 'image/gif') imagegif($imageBG, $pathB.'thumb'.$size.$name); 
		else imagepng($imageBG, $pathB.'thumb'.$size.'_'.$name);
		$this->filename = $name;
		$this->big_thumbname = 'thumbs_big_'.$name;
		$this->small_thumbname = 'thumbs_small_'.$name;
		// return final value 
		if ($del)
			unlink($path);
		return ($stretch) ? 1 : 0;
	}
	function filename ($type="") {
		if ($type == 'big')
		return $this->big_thumbname;
		elseif ($type == 'small')
		return $this->small_thumbname;
		else
		return $this->filename;
	}
}
?>
виводитця вот так
PHP:
if ($_POST['submit']){
		   include 'image.php';
		    // class image.php
		$img = new Image;
		$mW = 350; $quality = 70; $mH = 263; $bg = '#000000'; $sW = 75; $sH = 56;
		$num = 
		$img->upload($i, $mW, $mH, $sW, $sH, $bg, $quality, true, true);	
		echo($img->filename('big'));
		echo($img->filename('small'));
		//echo($img->filename());
		$image = $img->filename('big');
		$image1 = $img->filename('small');
 
  • Заблокирован
  • #2
чесно говоря переделывать ваше желания нет, по этому выложу свою реализацию, может она не идеальная, но то что вам нужно вы увидите.
не много подправить вашу функцию и проблем не будет
форма отправляющая запрос

PHP:
<form action=\"add_image.php\" method=\"post\" enctype=\"multipart/form-data\">
					<input type=\"file\" name=\"photo[]\" size=\"50\" /><br>
					<input type=\"file\" name=\"photo[]\" size=\"50\" /><br>
					<input type=\"file\" name=\"photo[]\" size=\"50\" /><br>
					<input type=\"file\" name=\"photo[]\" size=\"50\" /><br>
					<input type=\"file\" name=\"photo[]\" size=\"50\" /><br>
					<input type=\"file\" name=\"photo[]\" size=\"50\" /><br>
					<input type=\"file\" name=\"photo[]\" size=\"50\" /><br>
					<br><br>
					<input type=\"submit\" name=\"go_add\" value=\"Добавить\" />
					</form>

фаил add_image.php

PHP:
 include ("../bd.php");
		 include("img_resize.php");

		$cat = $_GET['IDcat'];




        $date = date("Y-n-j");
              #работа с фотографиями


					   $i = 0;
			  while($i <= 6)
			  {
							$max_image_size		= 5000*1024;
							$max_image_width	= 4500;
							$max_image_height	= 4500;
							$valid_types 		=  array("gif","jpg", "png", "jpeg", "JPG", "GIF", "JPEG", "PNG", "Jpeg");


						if (!empty($_FILES['photo']['size'][$i]))
						{

							if (is_uploaded_file($_FILES['photo']['tmp_name'][$i])) {
								$filename = $_FILES['photo']['tmp_name'][$i];
								$ext = substr($_FILES['photo']['name'][$i],
									1 + strrpos($_FILES['photo']['name'][$i], "."));
								if (filesize($filename) > $max_image_size) {
									echo 'Error: File size > 5M.';
								} elseif (!in_array($ext, $valid_types)) {
									echo 'Error: Invalid file type.';
								} else

								{
						 			$size = GetImageSize($filename);
						 			if (($size) && ($size[0] < $max_image_width)
										&& ($size[1] < $max_image_height))

										{
											$key = rand(11111,99999);
										 $name_file[$i] = md5(date("YmdHis", time()).$key) . ".$ext";
										 $name_file_thumb[$i] = md5(date("YmdHis", time()).$key) . "_thumb.jpg";
										 $image = "../fotogallery/foto/$name_file[$i]";
										 //$image = "test/$name_file[$i]";
										if (@copy($filename, $image)) {
                                        	//echo "Error: moving fie failed.$name_file<br>$i";
										} else {
											echo "Error: moving fie failed.$filename";
										}

									}
									else
									{
										echo "Error: invalid image properties.$filename<br>$size[0]<br>$size[1]<br>$size<br>";
									}
								}
							}
							 else
							{
								echo "Error: empty file.";
							}
							img_resize("../fotogallery/foto/$name_file[$i]", "../fotogallery/foto/$name_file_thumb[$i]", 150, 250,  85, 0xFFFFF0, 0);

							$url_photo = $name_file[$i];

	                        $url_photo_thumb = $name_file_thumb[$i];
                            $foto_name = trim(addslashes($_POST['name_foto'][$i]));
							#засовываем фото в базу


								$sql_add_foto_news = "
								INSERT INTO `fotogal`
								( `id_foto` , `name` , `url_foto` , `url_foto_thumb` , `popular` , `date` , `cat` )
								VALUES
								('', '$foto_name', '$url_photo', '$url_photo_thumb', '0', '$date', '$cat')";
								mysql_query($sql_add_foto_news) or die("Немогу добавить записи о фото");

						}

						$i = $i+1;
  				}

           header ("Location: /admin/?mod=foto_gal&act=add_foto&IDcat=$cat");
 
Статус
В этой теме нельзя размещать новые ответы.
Назад
Сверху