/** * Function that gets called on a job * Push::queue('smsSender', $emergency); * * @param $job * @param Emergency $emergency */ public function fire($job, $image) { $s3 = AWS::get('s3'); $image = Image::find($image['id']); if (!$image) { return $job->delete(); } try { $imageUtil = new ImageUtil($image->origin); $galleryImageUtil = new ImageUtil($image->origin); } catch (Exception $e) { return $job->delete(); } $image->thumbnail = $this->uploadImage($s3, $imageUtil->resize2('thumbnail')->getImage()); Log::debug("From queue: Thumbnail: width - {$imageUtil->getWidth()}, height - {$imageUtil->getHeight()}"); Log::debug("Thumbnail URL: {$image->thumbnail}"); $this->preventMemoryLeak(); $image->regular = $this->uploadImage($s3, $galleryImageUtil->resize2('gallery')->getImage()); Log::debug("From queue: Gallery: width - {$galleryImageUtil->getWidth()}, height - {$galleryImageUtil->getHeight()}"); Log::debug("Gallery URL: {$image->regular}"); $this->preventMemoryLeak(); $image->width = $galleryImageUtil->getWidth(); $image->height = $galleryImageUtil->getHeight(); $image->save(); return $job->delete(); }
public function loadFromPath($path) { $this->im = ImageUtil::getImFromPath($path); ImageUtil::addAlphaSave($this->im); $this->setWidth(imagesx($this->im)); $this->setHeight(imagesy($this->im)); return $this; }
public static function makeThumb($attach, $width, $height) { $attachUrl = FileUtil::getAttachUrl(); $file = sprintf("%s/%s", $attachUrl, $attach["attachment"]); $fileext = StringUtil::getFileExt($file); $thumbName = self::getThumbName($attach, $width, $height); if (LOCAL) { $res = ImageUtil::thumb2($file, $thumbName, "", $width, $height); } else { $tempFile = FileUtil::getTempPath() . "tmp." . $fileext; $orgImgname = Ibos::engine()->IO()->file()->fetchTemp(FileUtil::fileName($file), $fileext); ImageUtil::thumb2($orgImgname, $tempFile, "", $width, $height); FileUtil::createFile($thumbName, file_get_contents($tempFile)); } return $thumbName; }
/** * Output the image with the logos of each artist */ public function show() { if (count($this->artists) == 0) { throw new Exception("Missing some informations (artists)."); } $totalHeight = array(self::$marginTop, self::$marginTop); $listImageRessources = array(array(), array()); $forcedWidth = self::$width / 2 - self::$seperation / 2; foreach ($this->artists as $name) { if (count($listImageRessources[0]) + count($listImageRessources[1]) == $this->nbArtists) { break; } $a = Artists::getArtistByName($name); if ($a != null) { $image = Artists::imageFromArtist($a); if (isset($image)) { $i = $totalHeight[1] < $totalHeight[0] ? 1 : 0; $x = imagesx($image); $y = imagesy($image); $newHeight = floor($y * $forcedWidth / $x); $totalHeight[$i] += $newHeight + self::$seperation; array_push($listImageRessources[$i], $image); } } } $container = imagecreatetruecolor(self::$width, max($totalHeight)); //Some colors needed $colWhite = imagecolorallocate($container, 255, 255, 255); //Background color imagefilledrectangle($container, 0, 0, self::$width, max($totalHeight), $colWhite); $currentHeight = array(self::$marginTop, self::$marginTop); for ($l = 0; $l < count($listImageRessources); $l++) { $list = $listImageRessources[$l]; foreach ($list as $image) { $x = imagesx($image); $y = imagesy($image); $newHeight = floor($y * $forcedWidth / $x); $resized = imagecreatetruecolor($forcedWidth, $newHeight); imagecopyresampled($resized, $image, 0, 0, 0, 0, $forcedWidth, $newHeight, $x, $y); imagecopymerge($container, $resized, ($forcedWidth + self::$seperation) * $l, $currentHeight[$l], 0, 0, $forcedWidth, $newHeight, 100); //echo $currentHeight[$l] . "-"; $currentHeight[$l] += $newHeight + self::$seperation; } } ImageUtil::applyFilter($container, $this->color); imagepng($container); }
public function upload() { if (!Input::hasFile('image')) { return $this->respondNotFound('Image not found'); } $this->log('Started'); $this->log(memory_get_usage(true)); $attachment = new Image(); $this->file = Input::file('image'); $this->log('Init origin image'); $image = new ImageUtil($this->file); $this->log(memory_get_usage(true)); $this->log('Uploading origin image'); $this->log(memory_get_usage(true)); $attachment->origin = $this->uploadImage2($image->getImage()); $this->log(memory_get_usage(true)); // preventMemoryLeak(); $this->log('Garbage collector'); $this->log(memory_get_usage(true)); $this->log('Gallery image upload'); $attachment->regular = $this->uploadImage2($image->resize2('gallery')->getImage()); $this->log(memory_get_usage(true)); $this->log('Destroying gallery image'); $image->getImage()->destroy(); $image = null; $this->log(memory_get_usage(true)); // preventMemoryLeak(); $this->log('Garbage collector'); $this->log(memory_get_usage(true)); $this->log('Init thumbnail image'); $thumb = new ImageUtil($this->file); $thumb->resize2('thumbnail'); $this->log(memory_get_usage(true)); $this->log('uploading thumbnail image'); $attachment->thumbnail = $this->uploadImage2($thumb->getImage()); $this->log(memory_get_usage(true)); // preventMemoryLeak(); $this->log('Garbage collector'); $this->log(memory_get_usage(true)); $attachment->width = $thumb->getWidth(); $attachment->height = $thumb->getHeight(); $this->log('Destroying the thumb image'); $thumb->getImage()->destroy(); $thumb = null; $this->log(memory_get_usage(true)); $attachment->save(); return $this->respond($this->collectionTransformer->transformImage($attachment)); }
/** * Guardar un archivo en la BBDD. * * @param int $accountId * @param array $fileData con los datos y el contenido del archivo * @return bool */ public static function fileUpload($accountId, &$fileData = array()) { $query = "INSERT INTO accFiles " . "SET accfile_accountId = :accountId," . "accfile_name = :name," . "accfile_type = :type," . "accfile_size = :size," . "accfile_content = :blobcontent," . "accfile_extension = :extension," . "accfile_thumb = :thumbnail"; $data['accountId'] = $accountId; $data['name'] = $fileData['name']; $data['type'] = $fileData['type']; $data['size'] = $fileData['size']; $data['blobcontent'] = $fileData['content']; $data['extension'] = $fileData['extension']; $data['thumbnail'] = ImageUtil::createThumbnail($fileData['content'], $fileData['type']); if (DB::getQuery($query, __FUNCTION__, $data) === true) { $log = new Log(_('Subir Archivo')); $log->addDescription(_('Cuenta') . ": " . $accountId); $log->addDescription(_('Archivo') . ": " . $fileData['name']); $log->addDescription(_('Tipo') . ": " . $fileData['type']); $log->addDescription(_('Tamaño') . ": " . round($fileData['size'] / 1024, 2) . " KB"); $log->writeLog(); Email::sendEmail($log); return true; } return false; }
/** * Output the image with the logos of each artist */ public function show() { if (count($this->artists) == 0) { throw new Exception("Missing some informations (artists)."); } $totalHeight = 0; $listImageRessources = array(); foreach ($this->artists as $name) { if (count($listImageRessources) == $this->nbArtists) { break; } $a = Artists::getArtistByName($name); if ($a != null) { $image = Artists::imageFromArtist($a); if (isset($image)) { $totalHeight += imagesy($image) + self::$seperation; array_push($listImageRessources, $image); } } } //echo $totalHeight; $totalHeight += self::$marginTop; $container = imagecreatetruecolor(self::$width, $totalHeight); //Some colors needed $colWhite = imagecolorallocate($container, 255, 255, 255); //Background color imagefilledrectangle($container, 0, 0, self::$width, $totalHeight, $colWhite); $expectWidth = self::$width - 2 * self::$marginSide; $currentHeight = self::$marginTop; foreach ($listImageRessources as $image) { $widthImg = imagesx($image); //echo $this->width."-2 * ".self::$marginSide); //echo $widthImg."--".$expectWidth."<br/>"; imagecopymerge($container, $image, self::$marginSide + ($widthImg < $expectWidth ? ($expectWidth - $widthImg) * 0.5 : 0), $currentHeight, 0, 0, imagesx($image), imagesy($image), 100); $currentHeight += imagesy($image) + self::$seperation; } ImageUtil::applyFilter($container, $this->color); imagepng($container); }
/** * Invert color from an image ressource. * * @param ressource $image Image * "param string $color ID of a filter */ public static function applyFilter($image, $color) { if ($color == 'black') { ImageUtil::addInvertFilter($image); } else { if ($color == 'gray') { ImageUtil::addGrayFilter($image); } else { if ($color == 'blue') { self::addColorFilter($image, array(40, 79, 148)); } else { if ($color == 'red') { self::addColorFilter($image, array(214, 17, 2)); } else { if ($color == 'orange') { self::addColorFilter($image, array(222, 54, 0)); } else { if ($color == 'turquoise') { self::addColorFilter($image, array(69, 168, 196)); } else { if ($color == 'trans') { self::addTransFilter($image); } else { if ($color == 'white') { return; } else { throw new Exception("Unknown filter."); } } } } } } } } }
/** * sendMessage * * @param string $message Param * @param array $data Param * * @return bool */ public function sendMessage($message, $data) { $imagefile = null; try { $image_url = $data->image_url; $media_mode = $this->getMediaMode(); if ($media_mode != 'message' && !empty($image_url)) { $imagefile = ImageUtil::getInstance()->downloadImage($image_url); if ($imagefile) { $result = $this->_sendTwitterMessageWithImage($message, $imagefile); } else { $result = $this->_sendTwitterMessage($message, null); } } else { $result = $this->_sendTwitterMessage($message, $image_url); } } catch (Exception $e) { $result = array(false, $e->getMessage()); } if ($imagefile) { ImageUtil::getInstance()->releaseImage($imagefile); } return $result; }
function albumAction() { $img_id = $_SESSION['imag_id']; $imgAccount = ImgAccountUtil::getImgAccountById($img_id, TRUE); $v_params['sys_name'] = SysPropertiesUtil::getPropertyValue("sys_name"); $v_params['sys_slog'] = SysPropertiesUtil::getPropertyValue("sys_slog"); if (NULL != $imgAccount) { $v_params['logined'] = LoginChecker::isLogined(); if ($v_params['logined'] == $img_id) { $v_params['img_name'] = $imgAccount['img_name']; $v_params['mysc']['main'] = TRUE; $v_params['img_all_gds_cats_href'] = "/" . IMAG_PREFIX . $img_id . "/" . IMAG_DIR; $v_params['img_all_blog_cats_href'] = "/" . IMAG_PREFIX . $img_id . "/" . BLOG_DIR; $v_params['img_gds_cats_HTML'] = ImgGdsCatUtil::createTreeHTML($imgAccount['id'], "/" . IMAG_PREFIX . $img_id . "/" . IMAG_DIR . "?" . PROD_CAT_PARAM_NAME . "="); $v_params['img_blog_cats_HTML'] = ImgBlogCatUtil::createTreeHTML($imgAccount['id'], "/" . IMAG_PREFIX . $img_id . "/" . BLOG_DIR . "?" . ART_CAT_PARAM_NAME . "="); if (isset($_GET['act'])) { $action = $_GET['act']; if (0 == strcmp("add", $action)) { // Создать новый альбом $v_params['action_name'] = "Создать альбом"; if (isset($_POST['img_album_name'])) { $img_album_name = trim($_POST['img_album_name']); if (0 == strcmp("", $img_album_name)) { $v_params['messages'][] = "Имя альбома не может быть пустым"; } else { $imgAlbum['account_id'] = $imgAccount['id']; $imgAlbum['name'] = $img_album_name; $imgAlbum['description'] = $_POST['img_album_desc']; ImgAlbumUtil::insertImgAlbum($imgAlbum); $albumsURL = "/" . IMAG_PREFIX . $imgAccount['id'] . "/admin/albums"; header("Location: {$albumsURL}"); } } Application::fastView('imag-admin/albums/img_admin_album_au', $v_params); exit; } else { if (0 == strcmp("upd", $action)) { // Переименовать альбом $v_params['action_name'] = "Переименовать альбом"; if (isset($_GET['alb_id'])) { $imgAlbumId = $_GET['alb_id']; $imgAlbum = ImgAlbumUtil::getImgAlbumByID($imgAlbumId, $imgAccount['id']); if (NULL != $imgAlbum) { $v_params['img_album_name'] = $imgAlbum['name']; $v_params['img_album_desc'] = $imgAlbum['description']; } } else { $albumsURL = "/" . IMAG_PREFIX . $imgAccount['id'] . "/admin/albums"; header("Location: {$albumsURL}"); } if (isset($_POST['img_album_name'])) { $img_album_name = trim($_POST['img_album_name']); if (0 == strcmp("", $img_album_name)) { $v_params['messages'][] = "Имя альбома не может быть пустым"; } else { $imgAlbum['id'] = $imgAlbumId; $imgAlbum['account_id'] = $imgAccount['id']; $imgAlbum['name'] = $img_album_name; $imgAlbum['description'] = $_POST['img_album_desc']; ImgAlbumUtil::updateImgAlbum($imgAlbum); $albumsURL = "/" . IMAG_PREFIX . $imgAccount['id'] . "/admin/albums"; header("Location: {$albumsURL}"); } } Application::fastView('imag-admin/albums/img_admin_album_au', $v_params); exit; } else { if (0 == strcmp("del", $action)) { // Удалить альбом $v_params['action_name'] = "Удалить альбом"; if (isset($_GET['alb_id'])) { $imgAlbumId = $_GET['alb_id']; $imgAlbum = ImgAlbumUtil::getImgAlbumByID($imgAlbumId, $imgAccount['id']); if (NULL != $imgAlbum) { $v_params['img_album_name'] = $imgAlbum['name']; $v_params['img_album_desc'] = $imgAlbum['description']; $v_params['img_album_pict_count'] = ImgPictureUtil::countImgPicturesByAlbumId($imgAlbumId); } } else { $albumsURL = "/" . IMAG_PREFIX . $imgAccount['id'] . "/admin/albums"; header("Location: {$albumsURL}"); } if ($_POST['album_del_form']) { if ($_POST['with_pict']) { $img_pictures = ImgPictureUtil::getImgPicturesByAlbumId($imgAlbumId, $imgAccount['id']); if (count($img_pictures)) { foreach ($img_pictures as $img_pucture) { $file_path = dirname(__FILE__) . "/../../../application_data" . $img_pucture['path']; unlink($file_path); $path_blocks = explode("/", $img_pucture['path']); $last = count($path_blocks) - 1; $path_blocks[$last] = SMAL_PICT_PREFIX . $path_blocks[$last]; $path_small = implode("/", $path_blocks); $smal_file_path = dirname(__FILE__) . "/../../../application_data" . $path_small; unlink($smal_file_path); } } ImgAlbumUtil::deleteImgAlbumByID($imgAlbumId, TRUE); } else { ImgAlbumUtil::deleteImgAlbumByID($imgAlbumId, FALSE); } $albumsURL = "/" . IMAG_PREFIX . $imgAccount['id'] . "/admin/albums"; header("Location: {$albumsURL}"); } else { Application::fastView('imag-admin/albums/img_admin_album_del', $v_params); exit; } } else { if (0 == strcmp("show", $action)) { // Показать содержимое $v_params['action_name'] = "Содержимое альбома"; $alb_id = $_GET['alb_id']; $v_params['pict_control_url'] = "/" . IMAG_PREFIX . $imgAccount['id'] . "/admin/picture"; $v_params['img_album'] = ImgAlbumUtil::getImgAlbumByID($alb_id, $imgAccount['id']); if (NULL == $v_params['img_album']) { $v_params['img_album_name'] = "Картинки без альбома"; } else { $v_params['img_album_name'] = $v_params['img_album']['name']; } // Загрузка файлов if (NULL != $alb_id && NULL != $v_params['img_album'] || NULL == $alb_id) { if (isset($_FILES) && NULL != $_FILES['file']) { // директория для изображений $images_dir = dirname(__FILE__) . "/../../../application_data/images/"; foreach ($_FILES['file']['name'] as $k => $f) { if (!$_FILES['file']['error'][$k]) { if (is_uploaded_file($_FILES['file']['tmp_name'][$k])) { $fn = UUIDGenerator::generate(); $dir_path = $images_dir . "acc" . $imgAccount['id'] . "/"; $file_path = $dir_path . $fn; $rel_file_path = "/images/acc" . $imgAccount['id'] . "/" . $fn; @mkdir($dir_path, 0766); @ImageUtil::create_small($_FILES['file']['tmp_name'][$k], $file_path, SIZE_BIG_PICT, SIZE_BIG_PICT); @ImageUtil::create_small($file_path, $dir_path . SMAL_PICT_PREFIX . $fn, SIZE_SMAL_PICT, SIZE_SMAL_PICT); unlink($_FILES['file']['tmp_name'][$k]); $imgPicture['account_id'] = $imgAccount['id']; $imgPicture['album_id'] = $alb_id; $imgPicture['name'] = $_FILES['file']['name'][$k]; $imgPicture['path'] = $rel_file_path; ImgPictureUtil::createImgPicture($imgPicture); } } } } if (NULL == $alb_id) { $v_params['alb_pictures'] = ImgPictureUtil::getImgPicturesNoAlbum($imgAccount['id']); } else { $v_params['alb_pictures'] = ImgPictureUtil::getImgPicturesByAlbumId($alb_id, $imgAccount['id']); } Application::fastView('imag-admin/albums/img_admin_album_show', $v_params); return; } } } } } } } } Application::fastView('main/sys_error', $v_params); }
/** * Checks the validity of the given attachments. * Creates a user input error, if validation fails. * Returns true, if the given attachment is valid. * * @param string $tmpName path to attachment * @param string $fileHash sha1 hash of attachment * @param string $name original name of attachment * @param integer $size size of attachment * @param string $extension file extension of attachment * @return boolean true, if the given attachment is valid */ protected function checkAttachment($tmpName, $fileHash, $name, $size, $extension, $isImage) { $i = count($this->errors); if (isset($this->attachments[$this->messageID]) && count($this->attachments[$this->messageID]) > $this->maxUploads) { return false; } if (!$tmpName) { // php upload filesize limit reached $this->errors[$i]['attachmentName'] = $name; $this->errors[$i]['errorType'] = "fileSizePHP"; return false; } if (in_array($fileHash, $this->attachmentHashes)) { $this->errors[$i]['attachmentName'] = $name; $this->errors[$i]['errorType'] = "doubleUpload"; return false; } if ($size == 0 || $size > $this->maxFileSize) { $this->errors[$i]['attachmentName'] = $name; $this->errors[$i]['errorType'] = "fileSize"; return false; } if (!preg_match($this->allowedExtensions, $extension)) { $this->errors[$i]['attachmentName'] = $name; $this->errors[$i]['errorType'] = "illegalExtension"; return false; } if ($isImage && !ImageUtil::checkImageContent($tmpName)) { $this->errors[$i]['attachmentName'] = $name; $this->errors[$i]['errorType'] = "badImage"; return false; } return true; }
public function actionIndex() { $operation = EnvUtil::getRequest("op"); switch ($operation) { case "thumbpreview": case "waterpreview": $temp = Ibos::engine()->IO()->file()->getTempPath() . "/watermark_temp.jpg"; if (LOCAL) { if (is_file($temp)) { @unlink($temp); } } $quality = EnvUtil::getRequest("quality"); $source = PATH_ROOT . "/static/image/watermark_preview.jpg"; if ($operation == "waterpreview") { $trans = EnvUtil::getRequest("trans"); $type = EnvUtil::getRequest("type"); $val = EnvUtil::getRequest("val"); $pos = EnvUtil::getRequest("pos"); if ($type == "image") { $sInfo = ImageUtil::getImageInfo($source); $wInfo = ImageUtil::getImageInfo($val); if ($sInfo["width"] < $wInfo["width"] || $sInfo["height"] < $wInfo["height"]) { Ibos::import("ext.ThinkImage.ThinkImage", true); $imgObj = new ThinkImage(THINKIMAGE_GD); $imgObj->open($val)->thumb(260, 77, 1)->save($val); } ImageUtil::water($source, $val, $temp, $pos, $trans, $quality); } else { $hexColor = EnvUtil::getRequest("textcolor"); $size = EnvUtil::getRequest("size"); $fontPath = EnvUtil::getRequest("fontpath"); $rgb = ConvertUtil::hexColorToRGB($hexColor); ImageUtil::waterMarkString($val, $size, $source, $temp, $pos, $quality, $rgb, self::TTF_FONT_PATH . $fontPath); } $image = $temp; } if (!LOCAL) { if (Ibos::engine()->IO()->file()->createFile($temp, file_get_contents($image))) { $image = FileUtil::fileName($temp); } } $data = array("image" => $image, "sourceSize" => ConvertUtil::sizeCount(FileUtil::fileSize($source)), "thumbSize" => ConvertUtil::sizeCount(FileUtil::fileSize($image)), "ratio" => sprintf("%2.1f", FileUtil::fileSize($image) / FileUtil::fileSize($source) * 100) . "%"); $this->render("imagePreview", $data); exit; break; case "upload": return $this->imgUpload("watermark", true); break; } $formSubmit = EnvUtil::submitCheck("uploadSubmit"); $uploadKeys = "attachdir,attachurl,thumbquality,attachsize,filetype"; $waterMarkkeys = "watermarkminwidth,watermarkminheight,watermarktype,watermarkposition,watermarktrans,watermarkquality,watermarkimg,watermarkstatus,watermarktext,watermarkfontpath"; if ($formSubmit) { $keys = $uploadKeys . "," . $waterMarkkeys; $keyField = explode(",", $keys); foreach ($_POST as $key => $value) { if (in_array($key, $keyField)) { Setting::model()->updateSettingValueByKey($key, $value); } elseif ($key == "watermarkstatus") { Setting::model()->updateSettingValueByKey("watermarkstatus", 0); } } CacheUtil::update(array("setting")); $this->success(Ibos::lang("Save succeed", "message")); } else { $upload = Setting::model()->fetchSettingValueByKeys($uploadKeys); $waterMark = Setting::model()->fetchSettingValueByKeys($waterMarkkeys); $fontPath = DashboardUtil::getFontPathlist(self::TTF_FONT_PATH); $data = array("upload" => $upload, "waterMark" => $waterMark, "fontPath" => $fontPath); $this->render("index", $data); } }
/** * Creates a new avatar. * * @param string $tmpName * @param string $name * @param string $field * @return integer avatar id */ public static function create($tmpName, $name, $field, $userID = 0, $groupID = 0, $neededPoints = 0, $avatarCategoryID = 0) { // check avatar content if (!ImageUtil::checkImageContent($tmpName)) { throw new UserInputException($field, 'badAvatar'); } // get file extension /*$fileExtension = ''; if (!empty($name) && StringUtil::indexOf($name, '.') !== false) { $fileExtension = StringUtil::toLowerCase(StringUtil::substring($name, StringUtil::lastIndexOf($name, '.') + 1)); }*/ // get image data if (($imageData = @getImageSize($tmpName)) === false) { throw new UserInputException($field, 'badAvatar'); } // get file extension by mime $fileExtension = ImageUtil::getExtensionByMimeType($imageData['mime']); // check file extension if (!in_array($fileExtension, self::getAllowedFileExtensions())) { throw new UserInputException($field, 'notAllowedExtension'); } // get avatar size $width = $imageData[0]; $height = $imageData[1]; if (!$width || !$height) { throw new UserInputException($field, 'badAvatar'); } $size = @filesize($tmpName); // generate thumbnail if necessary if ($width > WCF::getUser()->getPermission('user.profile.avatar.maxWidth') || $height > WCF::getUser()->getPermission('user.profile.avatar.maxHeight')) { $thumbnail = new Thumbnail($tmpName, WCF::getUser()->getPermission('user.profile.avatar.maxWidth'), WCF::getUser()->getPermission('user.profile.avatar.maxHeight')); $thumbnailSrc = $thumbnail->makeThumbnail(); if ($thumbnailSrc) { $file = new File($tmpName); $file->write($thumbnailSrc); $file->close(); // refresh avatar size list($width, $height, ) = @getImageSize($tmpName); clearstatcache(); $size = @filesize($tmpName); // get new file extension $fileExtension = ImageUtil::getExtensionByMimeType($thumbnail->getMimeType()); } unset($thumbnail, $thumbnailSrc); } // check size again if ($width > WCF::getUser()->getPermission('user.profile.avatar.maxWidth') || $height > WCF::getUser()->getPermission('user.profile.avatar.maxHeight') || $size > WCF::getUser()->getPermission('user.profile.avatar.maxSize')) { throw new UserInputException($field, 'tooLarge'); } // create avatar $avatarID = self::insert(basename($name), array('avatarExtension' => $fileExtension, 'width' => $width, 'height' => $height, 'userID' => $userID, 'groupID' => $groupID, 'neededPoints' => $neededPoints, 'avatarCategoryID' => $avatarCategoryID)); // copy avatar to avatar folder if (!@copy($tmpName, WCF_DIR . 'images/avatars/avatar-' . $avatarID . '.' . $fileExtension)) { // copy failed // delete avatar @unlink($tmpName); $sql = "DELETE FROM\twcf" . WCF_N . "_avatar\n\t\t\t\tWHERE\t\tavatarID = " . $avatarID; WCF::getDB()->sendQuery($sql); throw new UserInputException($field, 'copyFailed'); } // set permissions @chmod(WCF_DIR . 'images/avatars/avatar-' . $avatarID . '.' . $fileExtension, 0666); return $avatarID; }
/** * getImageFromGalleryTag * * @param string $text Param. * * @return string */ public static function getImageFromGalleryTag($text) { if (!preg_match('/{gallery}([^\\:]+)\\:\\:\\:[0-9]+\\:[0-9]+{\\/gallery}/', $text, $matches)) { return null; } $folder = $matches[1]; $media = 'images/' . $folder; $galpath = JPATH_ROOT . '/' . $media; try { foreach (new DirectoryIterator($galpath) as $file) { $img = $galpath . '/' . $file->getFilename(); if ($file->isFile() && ImageUtil::isImage($img)) { return $media . '/' . $file->getFilename(); } } } catch (Exception $e) { } }
$telephone = $_POST['telephone']; $timezone = $_POST['timezone']; $image_name = basename($_FILES['user_image']['name']); $geocode = new Geocoder($street1, $city, $state, $zip); if ($image_name != "") { $pos = strpos($image_name, '.'); $img_ext = substr($image_name, $pos, strlen($image_name)); $modified_image_name = "P" . $username . $img_ext; $resourcedir = '/tmp/'; $user_image_location = $resourcedir . $modified_image_name; if (!move_uploaded_file($_FILES['user_image']['tmp_name'], $user_image_location)) { throw new Exception("Error moving uploaded file to {$user_image_location}"); } $imagethumb = "P" . $username . "T" . $img_ext; $thumb_location = $resourcedir . $imagethumb; ImageUtil::createThumb($user_image_location, $thumb_location, 133, 99); $fs = FileSystem::getInstance(); if (!$fs->create($user_image_location, "NO_OP", "NO_OP")) { error_log("Error copying image " . $user_image_location); } if (!$fs->create($thumb_location, "NO_OP", "NO_OP")) { error_log("Error copying thumb " . $thumb_location); } unlink($user_image_location); unlink($thumb_location); } else { $imgquery = "select imageurl from PERSON where username='******' "; $connection->beginTransaction(); $imgresult = $connection->query($imgquery); while ($imgresult->next()) { $modified_image_name = $imgresult->get(1);
/** * uploadImage * * @param string $image_url Param * * @return object */ public function uploadImage($image_url) { if (empty($image_url)) { return false; } $imagefile = ImageUtil::getInstance()->downloadImage($image_url); if (!$imagefile) { return false; } $status = false; try { $uid = $this->getUserId(); $gid = $this->channel->params->get('vkgroup_id'); $vk = $this->getApiInstance(); if ($gid) { $parameters = array('gid' => $gid); } else { $parameters = array('uid' => $uid); } $result = $vk->api('photos.getWallUploadServer', $parameters); if (array_key_exists('response', $result)) { $response = $result['response']; if (array_key_exists('upload_url', $response)) { $upload_url = $response['upload_url']; $ch = curl_init(); $data = array('photo' => '@' . $imagefile); curl_setopt($ch, CURLOPT_URL, $upload_url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $status = curl_exec($ch); if (!$status && curl_errno($ch)) { $logger = AutotweetLogger::getInstance(); $logger->log(JLog::ERROR, curl_error($ch)); } else { $status = json_decode($status); $photo = json_decode($status->photo); $parameters = array('server' => $status->server, 'photo' => $status->photo, 'hash' => $status->hash); if ($gid) { $parameters['gid'] = $gid; } else { $parameters['uid'] = $uid; } $status = $vk->api('photos.saveWallPhoto', $parameters); if (array_key_exists('response', $status) && is_array($status['response']) && count($status['response']) == 1) { $status = $status['response'][0]; } } curl_close($ch); } } if (array_key_exists('error', $result)) { $message = 'Error (' . $result['error']['error_code'] . ' ' . $result['error']['error_msg'] . ')'; $logger = AutotweetLogger::getInstance(); $logger->log(JLog::ERROR, $message); } } catch (Exception $e) { $logger = AutotweetLogger::getInstance(); $logger->log(JLog::ERROR, $e->getMessage()); } ImageUtil::getInstance()->releaseImage($imagefile); return $status; }
function get_turquoise($oldCol) { return ImageUtil::changeDarkToSpecColor(ImageUtil::getDarkerColor($oldCol, ImageUtil::GRAY_VALUE), array(69, 168, 196)); }
/** * publishRequest * * @param array $request Param * @param object $userid Param * * @return boolean */ public function publishRequest($request, $userid = null) { $this->logger->log(JLog::INFO, 'publishRequest request', $request); // Default: generate new entry for repost of entry with state success $postid = 0; $data = $this->_getContentData($request); if (!$data) { return false; } // Convert array to object $json = json_encode($data); $post = json_decode($json); if (AUTOTWEETNG_JOOCIAL) { $params = AdvancedattrsHelper::getAdvancedAttrByReq($request->id); } $post->ref_id = $request->ref_id; $post->plugin = $request->plugin; $post->postdate = $request->publish_up; $post->message = $post->text; unset($post->text); // Url if (isset($post->url) && !empty($post->url)) { $routeHelp = RouteHelp::getInstance(); $url = $routeHelp->getAbsoluteUrl($post->url); $post->url = $url; } elseif (isset($request->url) && !empty($request->url)) { $post->url = $request->url; } else { $this->logger->log(JLog::INFO, 'publishRequest: No url'); $post->url = ''; } $this->logger->log(JLog::INFO, 'publishRequest: url = ' . $post->url); // Image url if (isset($post->image_url) && !empty($post->image_url)) { // If defined in getExtendedData, use this image_url $routeHelp = RouteHelp::getInstance(); $url = $routeHelp->getAbsoluteUrl($post->image_url); // Only if it's a valid Url if (!ImageUtil::getInstance()->isValidImageUrl($url)) { $url = null; } $post->image_url = $url; } elseif (isset($request->image_url) && !empty($request->image_url)) { $url = $request->image_url; // Only if it's a valid Url if (!ImageUtil::getInstance()->isValidImageUrl($url)) { $url = null; } // Use this image_url (it's already routed) $post->image_url = $url; } else { $this->logger->log(JLog::INFO, 'publishRequest: No image url'); $post->image_url = null; } $this->logger->log(JLog::INFO, 'publishRequest: image url = ' . $post->image_url); // Title // Truncate title and fulltext for new messages ('if' is for backward compatibillity) if (isset($post->title)) { $title = TextUtil::cleanText($post->title); $post->title = TextUtil::truncString($title, self::MAX_CHARS_TITLE); } else { $post->title = ''; } // Fulltext if (!isset($post->fulltext)) { $post->fulltext = ''; } if (AUTOTWEETNG_JOOCIAL) { if (isset($params->fulltext) && !empty($params->fulltext)) { $post->fulltext = $params->fulltext; } } if (AUTOTWEETNG_JOOCIAL && EParameter::getComponentParam(CAUTOTWEETNG, 'paywall_mode') && ($fulltext = EParameter::getComponentParam(CAUTOTWEETNG, 'paywall_titleonly'))) { $post->fulltext = $fulltext; } $fulltext = TextUtil::cleanText($post->fulltext); $post->fulltext = TextUtil::truncString($fulltext, self::MAX_CHARS_FULLTEXT); $post->xtform = new JRegistry(); // Catids if (isset($post->catids)) { $catids = $post->catids; unset($post->catids); $post->xtform->set('catids', $catids); } else { $post->xtform->set('catids', array()); } // Author if (isset($post->author)) { $author = $post->author; unset($post->author); $post->xtform->set('author', $author); } // Language if (isset($post->language)) { $language = $post->language; unset($post->language); $post->xtform->set('language', $language); } // Access if (isset($post->access)) { $access = $post->access; unset($post->access); $post->xtform->set('access', $access); } // Target_id if (isset($post->target_id)) { $target_id = $post->target_id; unset($post->target_id); $post->xtform->set('target_id', $target_id); } // Hashtags if (isset($post->hashtags)) { $hashtags = $post->hashtags; unset($post->hashtags); $post->xtform->set('hashtags', $hashtags); } // Native object if (isset($request->native_object)) { $native_object = $request->native_object; $native_object = json_decode($native_object); if ($native_object) { $post->xtform->set('native_object', $native_object); } else { $this->logger->log(JLog::INFO, 'publishRequest: Inavlid JSON native_object'); } } // Featured if (isset($post->featured)) { $post->xtform->set('featured', $post->featured); unset($post->featured); } return $this->sendRequest($request, $post, $userid); }
public function &createIm($w, $h, $r, $g, $b, $a) { $im = imagecreatetruecolor($w, $h); imagealphablending($im, false); imagesavealpha($im, true); imagefill($im, 0, 0, imagecolorallocatealpha($im, $r, $g, $b, ImageUtil::percentToAlpha($a))); return $im; }
private function addPicture($attach, $articleId) { $sort = 0; foreach ($attach as $value) { $picture = array("articleid" => $articleId, "aid" => $value["aid"], "sort" => $sort, "addtime" => TIMESTAMP, "postip" => StringUtil::getSubIp(), "filename" => $value["filename"], "title" => "", "type" => $value["filetype"], "size" => $value["filesize"], "filepath" => $value["attachment"]); if (Yii::app()->setting->get("setting/articlethumbenable")) { list($thumbWidth, $thumbHeight) = explode(",", Yii::app()->setting->get("setting/articlethumbwh")); $imageInfo = ImageUtil::getImageInfo(FileUtil::fileName($picture["filepath"])); if ($imageInfo["width"] < $thumbWidth && $imageInfo["height"] < $thumbHeight) { $picture["thumb"] = 0; } else { $sourceFileName = explode("/", $picture["filepath"]); $sourceFileName[count($sourceFileName) - 1] = "thumb_" . $sourceFileName[count($sourceFileName) - 1]; $thumbName = implode("/", $sourceFileName); if (LOCAL) { ImageUtil::thumb($picture["filepath"], $thumbName, $thumbWidth, $thumbHeight); } else { $tempFile = FileUtil::getTempPath() . "tmp." . $picture["type"]; $orgImgname = Ibos::engine()->IO()->file()->fetchTemp(FileUtil::fileName($picture["filepath"]), $picture["type"]); ImageUtil::thumb($orgImgname, $tempFile, $thumbWidth, $thumbHeight); FileUtil::createFile($thumbName, file_get_contents($tempFile)); } $picture["thumb"] = 1; } } ArticlePicture::model()->add($picture); $sort++; } }
/** * _validateImages * * @param array &$images Params * @param bool $onlyFirstValid Params * * @return bool */ private function _validateImages(&$images, $onlyFirstValid = false) { $imgs = array(); $imageHelper = ImageUtil::getInstance(); foreach ($images as $image) { $imageUrl = $image->src; if ($imageHelper->isValidImageUrl($imageUrl)) { $imgs[] = $image; if ($onlyFirstValid) { break; } } } $images = $imgs; }
private function createColorImg($saveName, $val, $fontsize = 15) { $hexColor = EnvUtil::getRequest("quicknavcolor"); $tempFile = $this->getTempByHex($hexColor); if (!$tempFile) { $this->error(Ibos::lang("Quicknav add faild"), $this->createUrl("quicknav/index")); } $outputFile = $this->_iconPath . $saveName; $rgb = array("r" => 255, "g" => 255, "b" => 255); ImageUtil::waterMarkString($val, $fontsize, $tempFile, $outputFile, 5, 100, $rgb, self::TTF_FONT_File); return true; }
/** * download * * @param array $params Params * * @return bool */ public function download($params) { $logger = AutotweetLogger::getInstance(); $rel_src = $params->get('rel_src'); $img_folder = $params->get('img_folder'); $sub_folder = $params->get('sub_folder'); $img_name_type = $params->get('img_name_type'); $imageHelper = ImageUtil::getInstance(); $filename = $imageHelper->downloadImage($this->src); if (!$filename || !file_exists($filename)) { $logger->log(JLog::ERROR, 'download: failed ' . $this->src); return false; } // Main folder $path = JPATH_ROOT . DIRECTORY_SEPARATOR . $img_folder; // Sub folder $path_subfolder = $this->_getSubfolder($path, $sub_folder); if (!JFolder::exists($path_subfolder)) { $result = JFolder::create($path_subfolder); if (!$result) { $imageHelper->releaseImage($filename); $logger->log(JLog::ERROR, 'download: JFolder::create subfolder ' . $path_subfolder); return false; } } $img_filename = $this->_getImgFilename($filename, $img_name_type); $final_filename = $path_subfolder . DIRECTORY_SEPARATOR . $img_filename; $result = JFile::move($filename, $final_filename); if (!$result) { $imageHelper->releaseImage($filename); $logger->log(JLog::ERROR, 'download: JFile::move ' . $filename . ' - ' . $final_filename); return false; } $imgurl = str_replace(JPATH_ROOT . DIRECTORY_SEPARATOR, '', $final_filename); $this->original_src = $this->src; if ($rel_src) { $this->src = $imgurl; } else { $this->src = RouteHelp::getInstance()->getRoot() . $imgurl; } return true; }
public function attach($id) { $chat = CarChat::find($id); if (!$chat) { return $this->respondNotFound(); } if (!$chat->isMember($this->user->id)) { return $this->respondInsufficientPrivileges('User is not the member of chat'); } if (!Input::hasFile('image')) { return $this->respondInsufficientPrivileges('No image'); } $file = Input::file('image'); if (!in_array($file->guessExtension(), ['png', 'gif', 'jpeg', 'jpg'])) { return $this->respondInsufficientPrivileges('Unsupported file extension'); } $attachment = new MessageAttachment(); $attachment->id = DB::select("select nextval('messages_attachments_id_seq')")[0]->nextval; $this->log('Init images'); $this->log(memory_get_usage(true)); $origin = new ImageUtil($file); $attachment->origin = $this->upload($attachment->id, 'origin', $origin->getImage()); $attachment->gallery = $this->upload($attachment->id, 'gallery', $origin->resize2('gallery')->getImage()); $origin->getImage()->destroy(); $origin = null; $this->log('Images should be destroyed'); $this->log(memory_get_usage(true)); $this->log('Init thumbnail'); $thumb = (new ImageUtil($file))->resize2('thumbnail'); $attachment->thumb = $this->upload($attachment->id, 'thumb', $thumb->getImage()); $attachment->width = $thumb->getWidth(); $attachment->height = $thumb->getHeight(); $thumb->getImage()->destroy(); $thumb = null; $this->log('Thumbnail should be destroyed'); $this->log(memory_get_usage(true)); if ($chat->attachments()->save($attachment)) { $domain = 'http' . (Request::server('HTTPS') ? '' : 's') . '://' . Request::server('HTTP_HOST'); return $this->respond(['id' => $attachment->id, 'thumb' => $domain . '/api/carchats/' . $chat->id . '/attachments/' . $attachment->id, 'origin' => $domain . '/api/carchats/' . $chat->id . '/attachments/' . $attachment->id . '/gallery', 'width' => $attachment->width, 'height' => $attachment->height]); } $this->log(memory_get_usage(true)); return $this->respondServerError(); }
} else { // Limitation 1MB if (!isset($_FILES['profile']['error']) || is_array($_FILES['profile']['error'])) { $ret = HandleResponse::badRequestReturn("Failed to upload iamge"); } else { if ($_FILES['profile']['size'] > 1000000) { // 1MB limitation $ret = HandleResponse::badRequestReturn("Image is too big"); } else { $fp = fopen($_FILES["profile"]["tmp_name"], "rb"); // name=image $imgdat = fread($fp, filesize($_FILES["profile"]["tmp_name"])); fclose($fp); if ($imgdat != null) { // Image Check if (!ImageUtil::isSupport($imgdat)) { $ret = HandleResponse::badRequestReturn("Invalid image(please upload png or jpg"); } else { // Save Image $ret = updateImage($conn, $user_id, $imgdat); } } } } } mysqli_query($conn, "commit"); } catch (Exception $e) { mysqli_query($conn, "rollback"); $ret = HandleResponse::badRequestReturn($e->getMessage()); } print json_encode($ret);
public function setAvatar($img) { $s3 = AWS::get('s3'); $thumbnailPlaceholder = S3_PUBLIC . 'placeholder_128.png'; $profilePlaceholder = S3_PUBLIC . 'placeholder_64.png'; $imageUtil = new ImageUtil($img); $this->img_origin = $this->uploadImage($s3, $imageUtil->getImage()); $imageUtil->getImage()->destroy(); $imageUtil = null; preventMemoryLeak(); $imageUtil2 = new ImageUtil($img); $this->img_large = $this->uploadImage($s3, $imageUtil2->resize2('avatar.gallery')->getImage()); $imageUtil2->getImage()->destroy(); $imageUtil = null; preventMemoryLeak(); $imageUtil3 = new ImageUtil($img); $this->img_middle = $this->uploadImage($s3, $imageUtil3->resize2('avatar.profile')->getImage()) ?: $profilePlaceholder; $imageUtil3->getImage()->destroy(); $imageUtil3 = null; preventMemoryLeak(); $imageUtil4 = new ImageUtil($img); $this->img_small = $this->uploadImage($s3, $imageUtil4->resize2('avatar.thumbnail')->getImage()) ?: $thumbnailPlaceholder; $imageUtil4->getImage()->destroy(); $imageUtil4 = null; preventMemoryLeak(); }
} unset($litqresult); } } } // We end the DB transaction here. //$connection->commit(); // 9. Generate thumbnail and save images to file storage (outside tx) if ($image_name != "") { $resourcedir = '/tmp/'; $user_image_location = $resourcedir . $modified_image_name; if (!move_uploaded_file($_FILES['upload_image']['tmp_name'], $user_image_location)) { throw new Exception("Error moving uploaded file to {$modified_image_name}"); } $thumb_location = $resourcedir . $imagethumb; ImageUtil::createThumb($user_image_location, $thumb_location, 120, 120); if (!isset($fs)) { $fs = FileSystem::getInstance(); } if (!$fs->create($user_image_location, "NO_OP", "NO_OP")) { error_log("Error copying image " . $user_image_location); } if (!$fs->create($thumb_location, "NO_OP", "NO_OP")) { error_log("Error copying thumb " . $thumb_location); } unlink($user_image_location); unlink($thumb_location); } // 10. Save literature file to storage if ($literature_name != "") { $lit_resourcedir = '/tmp/';
#重采样拷贝部分图像并调整大小 ImageJpeg($nImg, $Image); #以JPEG格式将图像输出到浏览器或文件 return True; #如果是执行生成缩略图操作则 } else { $w = ImagesX($Img); $h = ImagesY($Img); $width = $w; $height = $h; $nImg = ImageCreateTrueColor($Dw, $Dh); if ($h / $w > $Dh / $Dw) { #高比较大 $width = $Dw; $height = $h * $Dw / $w; $IntNH = $height - $Dh; ImageCopyReSampled($nImg, $Img, 0, -$IntNH / 1.8, 0, 0, $Dw, $height, $w, $h); } else { #宽比较大 $height = $Dh; $width = $w * $Dh / $h; $IntNW = $width - $Dw; ImageCopyReSampled($nImg, $Img, -$IntNW / 1.8, 0, 0, 0, $width, $Dh, $w, $h); } ImageJpeg($nImg, $Image); return True; } } } $img = new ImageUtil(); $img->Img("d://p1606296118.jpg");
$this->image = imagerotate($this->image, $angle, 0); ob_start(); switch ($func) { case 'imagejpeg': $func($this->image); break; case 'imagepng': $func($this->image); break; default: $func($this->image); //quality 9. } $finalImage = ob_get_contents(); ob_end_clean(); imagedestroy($this->image); // free up memory $fp = @fopen($fileFullPath, 'w+'); @fwrite($fp, $finalImage); @fclose($fp); } } } $ImageUtil = new ImageUtil(); /** */ if ($argv[1] == 'resize') { $ImageUtil->resize($argv[2], $argv[3], $argv[4], $argv[5], $argv[6], $argv[7]); } elseif ($argv[1] == 'rotate') { $ImageUtil->createRotateImage($argv[2], $argv[3]); }
if ($_SERVER["REQUEST_METHOD"] == "GET") { $uuid = $_GET['key']; if (Validation::includeBlank($uuid)) { HandleResponse::badRequest("Parameters are blank"); } else { // Retrieve image data and analysis and show $conn = null; try { $db = new DBConnection(); $conn = $db->getConnection(); mysqli_query($conn, "set autocommit = 0"); mysqli_query($conn, "begin"); $image = getUserImage($conn, $uuid); mysqli_query($conn, "commit"); if ($image != null && ImageUtil::isSupport($image)) { header("Content-Type: " . ImageUtil::contentType($image)); echo $image; } else { // default image header("Content-Type: " . 'image/png'); $im = imagecreatefrompng("../../resources/defaultuser.png"); imagepng($im); imagedestroy($im); } } catch (Exception $e) { mysqli_query($conn, "rollback"); HandleResponse::badRequest($e->getMessage()); } } } else { // NOT GET request