|
0 / 0 / 0
Регистрация: 12.10.2010
Сообщений: 14
|
||||||
Уменьшить размер фото предобавлении на сайт12.10.2010, 16:12. Показов 3284. Ответов 6
Метки нет (Все метки)
Ребята помогите пожалуйста
вот скрипт upload фото и watermark
можна ли сделать так чтобы когда добавляю фото можна была уменьшить размер фото и поставить ограничении нап (1мб) и как сделать чтоб можна была менять места watermarkа y,x.
0
|
||||||
| 12.10.2010, 16:12 | |
|
Ответы с готовыми решениями:
6
Уменьшить размер фото
|
|
886 / 681 / 101
Регистрация: 23.01.2009
Сообщений: 1,582
|
||||||||||||||||
| 13.10.2010, 11:25 | ||||||||||||||||
|
Функцию process_image_upload меняем на:
0
|
||||||||||||||||
|
0 / 0 / 0
Регистрация: 12.10.2010
Сообщений: 14
|
|
| 13.10.2010, 13:29 [ТС] | |
|
0
|
|
|
0 / 0 / 0
Регистрация: 12.10.2010
Сообщений: 14
|
|
| 12.11.2010, 18:01 [ТС] | |
|
Добрый вечер,
У меня еще один вопрос, если я хочу не одну а несколько одновременно фото залить. Как тогда будет? и еще чтоб, когда они загрузились на них были и выводы
0
|
|
|
0 / 0 / 0
Регистрация: 12.10.2010
Сообщений: 14
|
|
| 14.12.2010, 15:57 [ТС] | |
|
ostgals, Добрый вечер,
У меня еще один вопрос, если я хочу не одну а несколько одновременно фото залить. Как тогда будет? и еще чтоб, когда они загрузились на них были и выводы.
0
|
|
|
886 / 681 / 101
Регистрация: 23.01.2009
Сообщений: 1,582
|
||||||||||||||||
| 16.12.2010, 10:46 | ||||||||||||||||
|
Меняем форму загрузки так, чтобы можно было выбрать несколько файлов. Как пример:
0
|
||||||||||||||||
|
0 / 0 / 0
Регистрация: 12.10.2010
Сообщений: 14
|
||
| 16.12.2010, 11:58 [ТС] | ||
|
Сперва я очень благодарен благодарен вам что вы поможете нам, часть не очень но я не очень. Вот наш скрипт: можете показать на этом скрипте? Заранее Спасибо. index.php <?php ob_start(); $disp_width_max=90; // used when displaying watermark choices $disp_height_max=80; // used when displaying watermark choices $edgePadding=15; // used when placing the watermark near an edge $quality=80; // used when generating the final image $default_watermark='Sample-trans.png'; // the default image to use if no watermark was chosen if(isset($_POST['process'])){ // an image has been posted, let's get to the nitty-gritty if(isset($_FILES['watermarkee']) && $_FILES['watermarkee']['error']==0){ // be sure that the other options we need have some kind of value if(!isset($_POST['save_as'])) $_POST['save_as']='jpeg'; if(!isset($_POST['v_position'])) $_POST['v_position']='bottom'; if(!isset($_POST['h_position'])) $_POST['h_position']='right'; if(!isset($_POST['wm_size'])) $_POST['wm_size']='0.25'; if(!isset($_POST['watermark'])) $_POST['watermark']=$default_watermark; // file upload success $size=getimagesize($_FILES['watermarkee']['tmp_name']); if($size[2]==2 || $size[2]==3){ // it was a JPEG or PNG image, so we're OK so far $original=$_FILES['watermarkee']['tmp_name']; $target_name=date('YmdHis').'_'. // if you change this regex, be sure to change it in generated-images.php:26 preg_replace('`[^a-z0-9-_.]`i','',$_FILES['watermarkee']['name']); $target=dirname(__FILE__).'/results/'.$target_name; $watermark=dirname(__FILE__).'/watermarks/'.$_POST['watermark']; $wmTarget=$watermark.'.tmp'; $max_w = 650; $max_h = 360; $size = getimagesize($original); $func = array(2 => 'jpeg', 3 => 'png'); $func_load = 'imagecreatefrom'.$func[$size[2]]; $func_save = 'image'.$func[$size[2]]; if (($sx = $size[0] / $max_w) > 1 || ($sy = $size[1] / $max_h) > 1) { $s = 1 / ($sx > $sy ? $sx : $sy); $w = $size[0] * $s; $h = $size[1] * $s; $dst = imagecreatetruecolor($w, $h); $src = $func_load($original); imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]); $func_save($dst, $original, 70); imagedestroy($src); imagedestroy($dst); } $origInfo = getimagesize($original); $origWidth = $origInfo[0]; $origHeight = $origInfo[1]; $waterMarkInfo = getimagesize($watermark); $waterMarkWidth = $waterMarkInfo[0]; $waterMarkHeight = $waterMarkInfo[1]; // watermark sizing info if($_POST['wm_size']=='larger'){ $placementX=0; $placementY=0; $_POST['h_position']='center'; $_POST['v_position']='center'; $waterMarkDestWidth=$waterMarkWidth; $waterMarkDestHeight=$waterMarkHeight; // both of the watermark dimensions need to be 5% more than the original image... // adjust width first. if($waterMarkWidth > $origWidth*1.05 && $waterMarkHeight > $origHeight*1.05){ // both are already larger than the original by at least 5%... // we need to make the watermark *smaller* for this one. // where is the largest difference? $wdiff=$waterMarkDestWidth - $origWidth; $hdiff=$waterMarkDestHeight - $origHeight; if($wdiff > $hdiff){ // the width has the largest difference - get percentage $sizer=($wdiff/$waterMarkDestWidth)-0.05; }else{ $sizer=($hdiff/$waterMarkDestHeight)-0.05; } $waterMarkDestWidth-=$waterMarkDestWidth * $sizer; $waterMarkDestHeight-=$waterMarkDestHeight * $sizer; }else{ // the watermark will need to be enlarged for this one // where is the largest difference? $wdiff=$origWidth - $waterMarkDestWidth; $hdiff=$origHeight - $waterMarkDestHeight; if($wdiff > $hdiff){ // the width has the largest difference - get percentage $sizer=($wdiff/$waterMarkDestWidth)+0.05; }else{ $sizer=($hdiff/$waterMarkDestHeight)+0.05; } $waterMarkDestWidth+=$waterMarkDestWidth * $sizer; $waterMarkDestHeight+=$waterMarkDestHeig ht * $sizer; } }else{ $waterMarkDestWidth=round($origWidth * floatval($_POST['wm_size'])); $waterMarkDestHeight=round($origHeight * floatval($_POST['wm_size'])); if($_POST['wm_size']==1){ $waterMarkDestWidth-=2*$edgePadding; $waterMarkDestHeight-=2*$edgePadding; } } // OK, we have what size we want the watermark to be, time to scale the watermark image resize_png_image($watermark,$waterMarkDe stWidth,$waterMarkDestHeight,$wmTarget); // get the size info for this watermark. $wmInfo=getimagesize($wmTarget); $waterMarkDestWidth=$wmInfo[0]; $waterMarkDestHeight=$wmInfo[1]; $differenceX = $origWidth - $waterMarkDestWidth; $differenceY = $origHeight - $waterMarkDestHeight; // where to place the watermark? switch($_POST['h_position']){ // find the X coord for placement case 'left': $placementX = $edgePadding; break; case 'center': $placementX = round($differenceX / 2); break; case 'right': $placementX = $origWidth - $waterMarkDestWidth - $edgePadding; break; } switch($_POST['v_position']){ // find the Y coord for placement case 'top': $placementY = $edgePadding; break; case 'center': $placementY = round($differenceY / 2); break; case 'bottom': $placementY = $origHeight - $waterMarkDestHeight - $edgePadding; break; } if($size[2]==3) $resultImage = imagecreatefrompng($original); else $resultImage = imagecreatefromjpeg($original); imagealphablending($resultImage, TRUE); $finalWaterMarkImage = imagecreatefrompng($wmTarget); $finalWaterMarkWidth = imagesx($finalWaterMarkImage); $finalWaterMarkHeight = imagesy($finalWaterMarkImage); imagecopy($resultImage, $finalWaterMarkImage, $placementX, $placementY, 0, 0, $finalWaterMarkWidth, $finalWaterMarkHeight ); if($size[2]==3){ imagealphablending($resultImage,FALSE); imagesavealpha($resultImage,TRUE); imagepng($resultImage,$target,$quality); }else{ imagejpeg($resultImage,$target,$quality) ; } imagedestroy($resultImage); imagedestroy($finalWaterMarkImage); // display resulting image for download ?> <div><p> <br> <table width="960px" align="center"><tr> <td align=right><b>Birbaşa keçid:</b></td> <td><input type="text" size="85" onFocus="copy(this);" value="http://www.test.ru/img/results/<?php echo $target_name ?>"></td></tr> <td align=right><b>Forum üçün keçid:</b></td> <td><input type="text" size="85" onFocus="copy(this);" value="<?php echo $target_name ?>"></td></tr> <td align=right><b>Forum üçün foto:</b></td> <td><input type="text" size="85" onFocus="copy(this);" value=" </table> </p> <p align="center"> <a href="/results/<?php echo $target_name ?>"><img src="results/<?php echo $target_name ?>?id=<?php echo md5(time()) ?>" alt="" border="0" /></a> </p> <hr> </div> <?php unlink($wmTarget); }else{ ?> <div> <h1>Foto yükləmə xidməti</h1> <p class="errorMsg">Yukləmək istədiyini foto (JPEG, JPG) olmalıdır.</p> </div> <?php } }else{ ?> <div> <h1>erorr</h1> <p class="errorMsg">Erorr.</p> </div> <?php } }else{ // no image posted, show form for options ?> <div><form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'] ?>"> <input type="file" size="79" name="watermarkee" /> <input type="hidden" name="MAX_FILE_SIZE" value="2012000" /> <Table class="file_list"><TR><TD nowrap> <b>1,5Mb (JPEG, JPG, formatlarda)</b><br> <div id="files_list" style="font: 12px Arial;"></div> </TD></TR></Table> <br> <table width="738" border="0"> <tr> <td > </td> <td aling="right"> <?php $dir=dirname(__FILE__).'/watermarks'; if (is_dir($dir)) { if ($dh = opendir($dir)) { $i=0; $watermarks=array(); while (($file = readdir($dh)) !== FALSE) { if(!preg_match('`\.png$`',$file)) continue; $watermarks[]=$file; } closedir($dh); // now sort the array according to file name asort($watermarks); foreach($watermarks as $file){ // restrain display width $size=getimagesize($dir.'/'.$file); if($size[0] > $disp_width_max && $disp_width_max){ $reduction=$disp_width_max / $size[0]; $size[0]=$size[0]*$reduction; $size[1]=$size[1]*$reduction; $size[3]=sprintf('width="%d" height="%d"',$size[0],$size[1]); // also restrain the height after a resize if($size[1] > $disp_height_max && $disp_height_max){ $reduction=$disp_height_max / $size[1]; $size[0]=$size[0]*$reduction; $size[1]=$size[1]*$reduction; $size[3]=sprintf('width="%d" height="%d"',$size[0],$size[1]); } } // also restrain the height if($size[1] > $disp_height_max && $disp_height_max){ $reduction=$disp_height_max / $size[1]; $size[0]=$size[0]*$reduction; $size[1]=$size[1]*$reduction; $size[3]=sprintf('width="%d" height="%d"',$size[0],$size[1]); } echo ' ',"\n", ' ',"\n", ' <input type="radio" value="',$file,'" name="watermark" /> ', '<img src="watermarks/',$file,'" ',$size[3],' alt="" />',"\n", ' ',"\n", ' ',"\n"; $i++; } if($i==0){ // no images at this time echo ' <tr>',"\n", ' <td>',"\n", ' There are currently no watermark images to use with this the system on this server.',"\n", ' </td>',"\n", ' </tr>',"\n"; } } } ?></td> </tr> </table> <center> <input type="checkbox" name="tos" value="1" id="tos" checked onClick="if(this.checked){$('submit_btn' ).disabled=false}else{$('submit_btn').di sabled=true};this.blur();"><br> <input type="submit" name="process" class="btn" value=" upload" /> </center> </form> <br><br> </div> <?php } $page_display=ob_get_clean(); function resize_png_image($img,$newWidth,$newHeig ht,$target){ $srcImage=imagecreatefrompng($img); if($srcImage==''){ return FALSE; } $srcWidth=imagesx($srcImage); $srcHeight=imagesy($srcImage); $percentage=(double)$newWidth/$srcWidth; $destHeight=round($srcHeight*$percentage )+1; $destWidth=round($srcWidth*$percentage)+ 1; if($destHeight > $newHeight){ // if the width produces a height bigger than we want, calculate based on height $percentage=(double)$newHeight/$srcHeight; $destHeight=round($srcHeight*$percentage )+1; $destWidth=round($srcWidth*$percentage)+ 1; } $destImage=imagecreatetruecolor($destWid th-1,$destHeight-1); if(!imagealphablending($destImage,FALSE) ){ return FALSE; } if(!imagesavealpha($destImage,TRUE)){ return FALSE; } if(!imagecopyresampled($destImage,$srcIm age,0,0,0,0,$destWidth,$destHeight,$srcW idth,$srcHeight)){ return FALSE; } if(!imagepng($destImage,$target)){ return FALSE; } imagedestroy($destImage); imagedestroy($srcImage); return TRUE; } echo '<?xml version="1.0" encoding="iso-8859-1"?>',"\n"; ?> <!--[if lt IE 7]><script src="/ie7/ie7-standard.js" type="text/javascript"></script><![endif]--> <div align="center" > <?php echo $page_display ?> </div> generated-images.php <?php /* KOIVI GD Image Watermarker for PHP Copyright (C) 2004 Justin Koivisto Version 2.0 Last Modified: 12/9/2004 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Full license agreement notice can be found in the LICENSE file contained within this distribution package. */ // capture output for later ob_start(); $disp_width_max=300; // used when displaying watermark choices $disp_height_max=300; // used when displaying watermark choices if(isset($_GET['delete'])){ // delete one of these images - use the regex to be sure that people aren't passing file paths to other places // in the system (ie. "../../../../../etc/passwd") $_GET['delete']=preg_replace('`[^a-z0-9-_.]`i','',$_GET['delete']); @unlink(dirname(__FILE__).'/results/'.$_GET['delete']); } ?> <div> <h1>Previously Watermarked Images</h1> <?php $dir=dirname(__FILE__).'/results'; if (is_dir($dir)) { if ($dh = opendir($dir)) { $i=0; echo ' <table cellpadding="3" cellspacing="0" border="0">',"\n"; $watermarks=array(); while (($file = readdir($dh)) !== FALSE) { if($file=='.' || $file=='..') continue; $watermarks[]=$file; } closedir($dh); // now sort the array according to file name asort($watermarks); foreach($watermarks as $file){ // restrain display width $size=getimagesize($dir.'/'.$file); if($size[0] > $disp_width_max && $disp_width_max){ $reduction=$disp_width_max / $size[0]; $size[0]=$size[0]*$reduction; $size[1]=$size[1]*$reduction; $size[3]=sprintf('width="%d" height="%d"',$size[0],$size[1]); // also restrain the height after a resize if($size[1] > $disp_height_max && $disp_height_max){ $reduction=$disp_height_max / $size[1]; $size[0]=$size[0]*$reduction; $size[1]=$size[1]*$reduction; $size[3]=sprintf('width="%d" height="%d"',$size[0],$size[1]); } } // also restrain the height if($size[1] > $disp_height_max && $disp_height_max){ $reduction=$disp_height_max / $size[1]; $size[0]=$size[0]*$reduction; $size[1]=$size[1]*$reduction; $size[3]=sprintf('width="%d" height="%d"',$size[0],$size[1]); } echo ' <tr>',"\n", ' <td>',"\n", ' <a href="results/',$file,'" target="_blank"><img src="results/',$file,'?id=', md5(time()),'" ',$size[3],' border="0" alt=""/></a>',"\n", ' </td>',"\n", ' <td>',"\n", ' <a href="',$_SERVER['PHP_SELF'],'?delete=',$file,'">Delete Image</a>',"\n", ' </td>',"\n", ' </tr>',"\n"; $i++; } if($i==0){ // no images at this time echo ' <tr>',"\n", ' <td>',"\n", ' There are currently no watermarked images saved on the system.',"\n", ' </td>',"\n", ' </tr>',"\n"; } echo ' </table>',"\n", ' </div>',"\n\n"; } } $page_display=ob_get_clean(); ?> <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Watermarking JPEG and PNG Images with PHP and GD2: Watermarked Images</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <!--[if lt IE 7]><script src="/ie7/ie7-standard.js" type="text/javascript"></script><![endif]--> </head> <body> <?php echo $page_display ?> </div> </div> </body> </html>
0
|
||
| 16.12.2010, 11:58 | |
|
Помогаю со студенческими работами здесь
7
Наложение текста на фото при загрузке фото на сайт Уменьшить объем фото
Уменьшить вес фото для сохранения в БД Искать еще темы с ответами Или воспользуйтесь поиском по форуму: |
|
Новые блоги и статьи
|
|||
|
SDL3 для Web (WebAssembly): сборка C/C++ проекта из консоли
8Observer8 30.01.2026
Содержание блога
Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
|
Установка Emscripten SDK (emsdk) и CMake на Windows для сборки C и C++ приложений в WebAssembly (Wasm)
8Observer8 30.01.2026
Чтобы скачать Emscripten SDK (emsdk) необходимо сначало скачать и уставить Git: Install for Windows. Следуйте стандартной процедуре установки Git через установщик. Система контроля версиями Git. . .
|
Подключение Box2D v3 к SDL3 для Android: физика и отрисовка коллайдеров
8Observer8 29.01.2026
Содержание блога
Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами. Версия v3 была полностью переписана на Си, в. . .
|
Инструменты COM: Сохранение данный из VARIANT в файл и загрузка из файла в VARIANT
bedvit 28.01.2026
Сохранение базовых типов COM и массивов (одномерных или двухмерных) любой вложенности (деревья) в файл, с возможностью выбора алгоритмов сжатия и шифрования.
Часть библиотеки BedvitCOM
Использованы. . .
|
|
Загрузка PNG с альфа-каналом на SDL3 для Android: с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 28.01.2026
Содержание блога
SDL3 имеет собственные средства для загрузки и отображения PNG-файлов с альфа-каналом и базовой работы с ними. В этой инструкции используется функция SDL_LoadPNG(), которая. . .
|
Загрузка PNG с альфа-каналом на SDL3 для Android: с помощью SDL3_image
8Observer8 27.01.2026
Содержание блога
SDL3_image - это библиотека для загрузки и работы с изображениями. Эта пошаговая инструкция покажет, как загрузить и вывести на экран смартфона картинку с альфа-каналом, то есть с. . .
|
Влияние грибов на сукцессию
anaschu 26.01.2026
Бифуркационные изменения массы гриба происходят тогда, когда мы уменьшаем массу компоста в 10 раз, а скорость прироста биомассы уменьшаем в три раза. Скорость прироста биомассы может уменьшаться за. . .
|
Воспроизведение звукового файла с помощью SDL3_mixer при касании экрана Android
8Observer8 26.01.2026
Содержание блога
SDL3_mixer - это библиотека я для воспроизведения аудио. В отличие от инструкции по добавлению текста код по проигрыванию звука уже содержится в шаблоне примера. Нужно только. . .
|