public function AddPhotoFile() { //Сначала кидаем изображение в _big, потом копируем два файла в _preview и _small, потом масштабируем их $filename = isset($this->request['FileName']) ? $this->request['FileName'] : ''; //собственно имя файла $fileid = isset($this->request['FileID']) ? $this->request['FileID'] : ''; //имя КАТЕГОРИИ файла (например b2b, b2c, b2fr...) без постфиксов (_big и пр.) $data = isset($this->request['Data']) ? utf8_decode($this->request['Data']) : ''; //получили данные //$filename = md5($data); if (strlen($filename) < 3) { return 'FileName must be set!'; } // Проверяем, существуют ли ТРИ папки хранилища, куда будут класться отмасштабированные картинки (если нет, пробуем создать их с правами chmod 777) $savepath_big = $this->config['storage'] . DIRECTORY_SEPARATOR . $fileid . '_big'; if (!file_exists($savepath_big)) { if (!mkdir($savepath_big, 0777, true)) { return 'Failed to save _big image file!'; } } $savepath_preview = $this->config['storage'] . DIRECTORY_SEPARATOR . $fileid . '_preview'; if (!file_exists($savepath_preview)) { if (!mkdir($savepath_preview, 0777, true)) { return 'Failed to save _preview image file!'; } } $savepath_small = $this->config['storage'] . DIRECTORY_SEPARATOR . $fileid . '_small'; if (!file_exists($savepath_small)) { if (!mkdir($savepath_small, 0777, true)) { return 'Failed to save _small image file!'; } } if (file_put_contents($savepath_big . DIRECTORY_SEPARATOR . $filename, $data) === FALSE) { //Пробуем переместить изображение в ..._big folder return 'Failed to save image file!'; } // if (copy($savepath_big . DIRECTORY_SEPARATOR . $filename, $savepath_preview . DIRECTORY_SEPARATOR . $filename) === FALSE) // if (copy($savepath_big . DIRECTORY_SEPARATOR . $filename, $savepath_small . DIRECTORY_SEPARATOR . $filename) === FALSE) // return 'Failed to copy image file!'; //пытаемся скопировать изображение в папки _preview и _small //Получаем параметры загруженного (в папку _big) изображения (ширина-высота, тип и пр.) list($i_width, $i_height, $i_type, $i_attr) = getimagesize($savepath_big . DIRECTORY_SEPARATOR . $filename); $small_max_size = 90; //Максимальный размер ширины/высоты small изображения $preview_max_size = 500; //Максимальный размер ширины/высоты preview изображения //Функция изменения размеров и преобразования изображения в формат jpeg function imageresize($outfile, $infile, $neww, $newh, $quality, $realtype) { if ($realtype == 2) { $im = imagecreatefromjpeg($infile); } if ($realtype == 3) { $im = imagecreatefrompng($infile); } if ($realtype == 1) { $im = imagecreatefromgif($infile); } if ($realtype == 6) { $im = imagecreatefromwbmp($infile); } $im1 = imagecreatetruecolor($neww, $newh); imagecopyresampled($im1, $im, 0, 0, 0, 0, $neww, $newh, imagesx($im), imagesy($im)); imagejpeg($im1, $outfile, $quality); imagedestroy($im); imagedestroy($im1); } //Задаем коэффициенты масштабирования $i_quo и $i_quo2 для preview и small соответственно if ($i_height > $i_width) { $i_quo = $i_height / $preview_max_size; $i_quo2 = $i_height / $small_max_size; } else { $i_quo = $i_width / $preview_max_size; $i_quo2 = $i_width / $small_max_size; } $f1 = $savepath_big . DIRECTORY_SEPARATOR . $filename; $fn = $savepath_preview . DIRECTORY_SEPARATOR . $filename; $fs = $savepath_small . DIRECTORY_SEPARATOR . $filename; // imageresize($f1,$f1,$i_width,$i_height,70,$i_type); imageresize($fn, $f1, $i_width / $i_quo, $i_height / $i_quo, 70, $i_type); //Масштабируем preview изображение imageresize($fs, $f1, $i_width / $i_quo2, $i_height / $i_quo2, 70, $i_type); //Масштабируем small изображение return 'OK'; }
// // phpinfo(); //setlocale(LC_CTYPE,'en_US.UTF-8'); //setlocale(LC_ALL,'en_US.UTF-8','en_EN'); //passthru('export LC_CTYPE=en_US.UTF-8;/usr/bin/locale'); echo "<br/>\n"; $testfile = 'part/one(two)[three];four| five'; echo $testfile . "<br/>\n"; echo "result=" . sanitizeFilename($testfile) . "<br/>\n"; $sql = "select upload_id,rel_file_path,mime_type from uploads where prjm_id=385 and mime_type ='image/jpeg'"; $resultSet = $dbConn->Execute($sql); if ($result !== false) { while (!$resultSet->EOF) { extract($resultSet->fields); $source = $upload_path_prefix . '/' . $rel_file_path; echo "upload_id={$upload_id} {$mime_type} {$source} <br/>\n"; $resized = imageresize($source); if ($resized > 0) { $sql2 = "update uploads set filesize={$resized} where upload_id={$upload_id}"; $dbConn->Execute($sql2); echo "RESIZED<br/>"; } $resultSet->moveNext(); } } //passthru('/home/hombergp/testsite/peer/locale.sh'); //$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension //foreach (glob("*") as $filename) { // echo "$filename=".finfo_file($finfo, $filename) . "\n"; //} //finfo_close($finfo);
if (preg_match('/image/i', $_FILES['xfile']['type'])) { $filename = $_POST['value'] ? $_POST['value'] : $folder . sha1(@microtime() . '-' . $_FILES['xfile']['name']) . '.jpg'; } else { $tld = split(',', $_FILES['xfile']['name']); $tld = $tld[count($tld) - 1]; $filename = $_POST['value'] ? $_POST['value'] : $folder . sha1(@microtime() . '-' . $_FILES['xfile']['name']) . $tld; } // Supporting image file types $types = array('image/png', 'image/gif', 'image/jpeg'); // File type control if (in_array($_FILES['xfile']['type'], $types)) { // Create an unique file name // Uploaded file source $source = file_get_contents($_FILES["xfile"]["tmp_name"]); // Image resize imageresize($source, $filename, $_POST['width'], $_POST['height'], $_POST['crop'], $_POST['quality']); } else { // If the file is not an image move_uploaded_file($_FILES["xfile"]["tmp_name"], $filename); } // File path $path = str_replace('upload.php', '', $_SERVER['SCRIPT_NAME']); // Result data $r->filename = $filename; $r->path = $path; $r->img = '<img src="' . $path . $filename . '" alt="image" />'; // Return to JSON echo json_encode($r); // Image resize function with php + gd2 lib function imageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) {
$tag = htmlspecialchars($_POST['tag']); $file_name = hash("md5", time() . rand()); $cursor = strpos($img, ',') + 1; $img = substr($img, $cursor); $img = base64_decode($img); $fd = finfo_open(); $info = finfo_buffer($fd, $img, FILEINFO_MIME_TYPE); finfo_close($fd); if (!strstr($info, "image/")) { $_POST['error'] = "No image file"; echo "Error file"; } else { $meme = prepare_posmeme($pos); unset($info, $cursor, $fd, $pos); $img = imagecreatefromstring($img); $img = imageresize($img, 320, 240); if (!$img) { $_POST['error'] = "Can't create image object"; echo "Error image object"; } else { $img = merge_to_finalimg($img, $meme); unset($meme); if (!$img) { $_POST['error'] = "Merged failed"; echo "Error merge"; } else { $trans = 0; try { $pdo = new PDO($DB_DSN, $DB_USER, $DB_PASSWORD); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec("USE db_camagru;");
$folder = $headers['x-param-folder'] ? $headers['x-param-folder'] . '/' : ''; if ($folder && !is_dir($folder)) { mkdir($folder); } // File type control if (in_array($headers['x-file-type'], $types)) { // Create an unique file name if ($headers['x-param-value']) { $filename = $folder . $headers['x-param-value']; } else { $filename = $folder . sha1(@date('U') . '-' . $headers['x-file-name']) . '.' . $headers['x-param-type']; } // Uploaded file source $source = file_get_contents($_FILES["x-file-name"]["tmp_name"]); // Image resize imageresize($source, $filename, $headers['x-param-width'], $headers['x-param-height'], $headers['x-param-crop'], $headers['x-param-quality']); } else { $r->error = "Unsupported file type: " . $headers['x-file-type']; } // File path $path = str_replace('upload.php', '', $_SERVER['SCRIPT_NAME']); // Image tag $r->filename = $filename; $r->path = $path; $r->img = '<img src="' . $path . $filename . '" alt="image" />'; echo json_encode($r); // Image resize function with php + gd2 lib function imageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) { $quality = $quality ? $quality : 80; $image = imagecreatefromstring($source);
$query = "DELETE FROM `users` WHERE `id`='{$_GET['del']}'"; mysql_query($query) or die(mysql_error()); header('Location: user.php?id=' . $_GET['id'] . '&mode=1'); } // cохранение аватарки if (isset($_GET['saveavatar'])) { $uploaddir = 'files/avatars/'; $tmp = time(); $ext = pathinfo($uploadfile . $_FILES['avatar']['name']); //$uploadfile = $uploaddir.basename($_FILES['avatar']['name']); $uploadfile = $uploaddir . $tmp . '.' . $ext['extension']; if (move_uploaded_file($_FILES['avatar']['tmp_name'], $uploadfile)) { //print $user->avatar; unlink($user->avatar); $file = 'files/avatars/' . $tmp . '.' . $ext['extension']; imageresize($file, $file, 30, 75); $user->avatar = $file; $user->save_settings(); $user->get_settings(); $_SESSION['user_class'] = serialize($user); } header('Location: user.php?id=' . $_GET['id']); } $sc = ' '; print_header("Профиль пользователя " . $user->username, $sc); ?> <script> function del_user(id,id_del,username) { if(confirm("Удалить пользователя "+username))
<!--//End-slider-script --> <div id="top" class="callbacks_container wow fadeInUp" data-wow-delay="0.5s"> <ul class="rslides" id="slider3"> <?php if ($slides) { ?> <?php foreach ($slides as $slide) { ?> <li> <div class="slide"> <img src="<?php echo imageresize(base_url($slide->imageName), 1920, 700); ?> " alt=""> <div class="slideText"> <h1><?php echo $slide->title; ?> </h1> <p><?php echo $slide->desc; ?> </p> <!--<a href="<?php echo $slide->link; ?> " class="hvr-shutter-out-horizontal">Read More</a>-->
?> </td> <td><?php echo $slide->title; ?> </td> <td><?php echo $slide->desc; ?> </td> <td><?php echo $slide->link; ?> </td> <td ><?php echo '<img src="' . imageresize(base_url($slide->imageName), 300, 200) . '">'; ?> </td> <td> <?php if (user_can('update', $modelName, $slide->id)) { ?> <a href="<?php echo base_url('slider/sliderbo/edit') . '/' . $slide->id; ?> "><i class="fa fa-pencil"></i></a> <?php } ?> </td> </tr>
mkdir($folder); } // File type control if (in_array($_SERVER['HTTP_X_FILE_TYPE'], $types)) { // Create an unique file name // if ($headers['x-param-value']) { // $filename = $folder . $headers['x-param-value']; // } else { $filename = $folder . sha1(@date('U') . '-' . $_SERVER['HTTP_X_FILE_NAME']) . '.' . $_SERVER['HTTP_X_PARAM_TYPE']; $filename_original = $folder . "orig-" . sha1(@date('U') . '-' . $_SERVER['HTTP_X_FILE_NAME']) . '.' . $_SERVER['HTTP_X_PARAM_TYPE']; // } // Uploaded file source $source = file_get_contents('php://input'); // Image resize file_put_contents($filename_original, $source); imageresize($source, $filename, $_SERVER['HTTP_X_PARAM_WIDTH'], $_SERVER['HTTP_X_PARAM_HEIGHT'], $_SERVER['HTTP_X_PARAM_CROP'], 60); } else { $r->error = "Unsupported file type: " . $_SERVER['HTTP_X_FILE_TYPE']; } // File path $path = str_replace('upload.php', '', $_SERVER['SCRIPT_NAME']); // Image tag $r->filename = $filename; $r->path = $path; $r->img = '<img src="' . $path . $filename . '" alt="image" />'; echo json_encode($r); // Image resize function with php + gd2 lib function imageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) { $quality = $quality ? $quality : 80; $image = imagecreatefromstring($source);
if ($error_flag == 0) { $name = preg_replace('~\\.tmp~', "", basename($myfile)); $f_thum = $_SERVER["DOCUMENT_ROOT"] . "/Upload/gallery/thum_" . $name . ".jpg"; print "Имя файла на сервере:" . $myfile . "<br>"; print "Имя файла на компьютере:" . $myfile_name . "<br>"; print "Имя будущей миниатюры на сервере:" . $f_thum . "<br>"; print "MIME тип файла:" . $myfile_type . "<br>"; print "Размер файла:" . $myfile_size . "<br>"; //если размер файла больше 1024 Кбайт if ($myfile_size > 1024 * 1024) { die("Размер файла превышает 1024 Кбайт. Уменьшите файл!"); } //копирование файла из временного каталога в галерею $fname = $_SERVER["DOCUMENT_ROOT"] . "/Upload/gallery/" . $name . ".jpg"; copy($myfile, $fname); //функция миниатюры function imageresize($infile, $outfile, $neww, $newh, $quality) { $im = imagecreatefromjpeg($infile); $im1 = imagecreatetruecolor($neww, $newh); imagecopyresampled($im1, $im, 0, 0, 0, 0, $neww, $newh, imagesx($im), imagesy($im)); imagejpeg($im1, $outfile, $quality); imagedestroy($im); imagedestroy($im1); } imageresize($fname, $f_thum, 260, 200, 75); } echo "<a href = '/'>На главную</a>"; } else { echo file_get_contents($_SERVER["DOCUMENT_ROOT"] . "/Views/gallery_form.html"); }
} // If the file is an image if (preg_match('/image/i', $_FILES['photo']['type'])) { $filename = 'uploads/' . uniqid() . '.jpg'; } else { $r->error = "Error: Only image files"; } // Supporting image file types $types = array('image/png', 'image/gif', 'image/jpeg'); // File type control if (in_array($_FILES['photo']['type'], $types)) { // Create an unique file name // Uploaded file source $source = file_get_contents($_FILES["photo"]["tmp_name"]); // Image resize imageresize($source, $filename); } else { // If the file is not an image $r->error = "Error: this is not an image file"; return false; } // File path $path = str_replace('uploader.php', '', $_SERVER['SCRIPT_NAME']); // Result data $r->filename = $filename; $r->path = $path; $r->img = '<img src="' . $r->path . $r->filename . '" alt="image" />'; // Return to JSON echo json_encode($r); // Image resize function with php + gd2 lib function imageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80)
echo "</div></div>"; } else { if (file_exists($location . $_FILES['image']['name'][$i])) { // FILE ALREADY EXISTS echo "<div class='adminError'>"; echo "<b>" . $_FILES['image']['name'][$i] . "</b> already exists on the server. Please upload another image."; echo "</div>"; } else { if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $location . "pavati-marine-gallery-image-" . $_FILES['image']['name'][$i])) { // SUCCESSFULLY UPLOADED IMAGE AND CREATED THUMBNAIL echo "<div class='adminThumbReturn'>"; echo "<img src='" . $thumbLocation . "pavati-marine-gallery-image-" . $_FILES['image']['name'][$i] . "' />"; echo "<p>" . $_FILES['image']['name'][$i] . "</p>"; echo "</div>"; $url = "pavati-marine-gallery-image-" . $_FILES['image']['name'][$i]; imageresize($location . "pavati-marine-gallery-image-" . $_FILES['image']['name'][$i], $thumbLocation . "pavati-marine-gallery-image-" . $_FILES['image']['name'][$i], 300, 200); mysql_query("INSERT INTO galleryimages (galleryimgcats, galleryimg) VALUES (\"{$model}\", \"{$url}\")"); } else { // IMAGE IS TOO LARGE echo "<div class='adminResults imageError'><div class='adminError'>"; echo "<b>" . $_FILES['image']['name'][$i] . "</b> is too large of a file. Please resize the image to be less than 2MB.<br>Recommended image size is 2,200 pixels by 1,650 pixels."; echo "</div></div>"; } } } } } else { } } else { } if ($_SESSION['admin']) {
imagepng($im1, $outfile, 9); } imagedestroy($im); imagedestroy($im1); } // Конвертируем изображение $whRatioCanvas = $__config['canvas']['width'] / $__config['canvas']['height']; $whRatioImage = $fileInfo[0] / $fileInfo[1]; if ($whRatioCanvas < $whRatioImage) { // Масштабируем по ширине $newWidth = $__config['canvas']['width']; $newHeight = $newWidth / $whRatioImage; } else { // Масштабируем по высоте $newHeight = $__config['canvas']['height']; $newWidth = $newHeight * $whRatioImage; } if ($newWidth < $fileInfo[0] || $newHeight < $fileInfo[1]) { imageresize($imgs['orig']['path'], $imgs['min']['path'], $newWidth, $newHeight, $fileInfo["mime"], 60); } else { $newWidth = $fileInfo[0]; $newHeight = $fileInfo[1]; copy($imgs['orig']['path'], $imgs['min']['path']); } // Формируем ответ echo json_encode(array('status' => 'success', 'imgName' => $imgs['orig']['name'], 'minName' => $imgs['min']['name'], 'newSize' => array('newWidth' => $newWidth, 'newHeight' => $newHeight), 'imgSize' => array('width' => $fileInfo[0], 'height' => $fileInfo[1])), JSON_FORCE_OBJECT); // Сохраняем данные об изображении в сессии $_SESSION["uploads"][$fileType]["origName"] = $_FILES[$fileType]['name']; $_SESSION["uploads"][$fileType]["tmpName"] = $imgs['orig']['name']; $_SESSION["uploads"][$fileType]["width"] = $fileInfo[0]; $_SESSION["uploads"][$fileType]["height"] = $fileInfo[1];
<?php switch ($file->type) { case 'image/png': case 'image/jpeg': case 'image/gif': ?> <img src="<?php echo imageresize($file->file, 20, 20); ?> " title="<?php echo $file->name; ?> "/> <?php break; case 'application/zip': case 'application/rar': ?> <i class="fa fa-file-archive-o"></i> <?php break; case 'application/pdf': ?> <i class="fa fa-file-pdf-o"></i> <?php break; default: ?> <i class="fa fa-file"></i> <?php
$name = implode('.', $file_array); //拼装新文件名(含扩展名) $file = $name . '_' . sha1(@microtime() . $_FILES['xfile']['name']) . '.' . $extension; //生成文件存放路径 $dir = 'dofiles/member/' . $_SESSION['member']['id'] . '/wallpaper/'; if (!is_dir($dir)) { //循环创建目录 recursive_mkdir($dir); } //获取原图宽高 $source = file_get_contents($_FILES["xfile"]["tmp_name"]); $image = imagecreatefromstring($source); $w = imagesx($image); $h = imagesy($image); //缩略图上传 imageresize($source, $dir . 's_' . $file, 150, 105); //原图上传 move_uploaded_file($_FILES['xfile']["tmp_name"], $dir . $file); //上传完毕后,添加数据库记录 $db->insert(0, 0, 'tb_pwallpaper', "url='" . $dir . $file . "', width={$w}, height={$h}, member_id = " . $_SESSION['member']['id']); $r->dir = $dir; $r->file = iconv('gb2312', 'UTF-8', $file); echo json_encode($r); break; case 'del': $db->delete(0, 0, 'tb_pwallpaper', "and tbid = {$id}"); break; default: $rs = $db->select(0, 1, 'tb_member', 'wallpapertype,wallpaperwebsite', 'and tbid = ' . $_SESSION['member']['id']); $smarty->assign('wallpaperType', $rs['wallpapertype']); $smarty->assign('wallpaperWebsite', $rs['wallpaperwebsite']);
function processImage($source, $destination, $newheight, $newwidth, $extension) { $source = str_replace('//', '/', $source); $destination = str_replace('//', '/', $destination); //echo $source; if (file_exists($source)) { $format_x = strtolower(str_replace('.', '', $extension)); list($width, $height) = getimagesize($source); $height_x = $height; $width_x = $width; if ($height > $newheight and $newheight > 0) { $height_x = $newheight; $width_x = $width / ($height / $height_x); } if ($width > $newwidth and $newwidth > 0) { $width_x = $newwidth; $height_x = $height / ($width / $width_x); } imageresize($source, $destination, $width_x, $height_x, $format_x); } }