public function ocr($billID, $template) { $amountImgFileDirectory = "images/detection_result/"; $dueDateImgFileDirectory = "images/detection_result/"; $amountImgFileName = "croppedAmt.jpg"; $dueDateImgFileName = "croppedDueDate.jpg"; //connect to mysql and getting the coordinate data require_once 'TesseractOCR.php'; $this->billdb->select('billFilePath'); $this->billdb->where('billID', $billID); $query1 = $this->billdb->get('bills'); //$this->billdb->query("SELECT billFilePath from bills where billID = " . $billID); $ini_filename = $query1->result()[0]->billFilePath; $im = imagecreatefromjpeg($ini_filename); list($width, $height) = getimagesize($ini_filename); $query2 = $this->templatedb->query("SELECT coordinateLabelX, coordinateLabelY, coordinateLabelX2, coordinateLabelY2 FROM datafields WHERE templateID = '" . $template . "' AND dataFieldLabel = 'amount'"); $row = $query2->row(0); $x1 = $row->coordinateLabelX; $y1 = $row->coordinateLabelY; $x2 = $row->coordinateLabelX2 - $row->coordinateLabelX; $y2 = $row->coordinateLabelY2 - $row->coordinateLabelY; // Scale Up coordinates $x1 = $x1 * $width; $y1 = $y1 * $height; $x2 = $x2 * $width; $y2 = $y2 * $height; //cropping the image using the coordinate data $to_crop_array = array('x' => $x1, 'y' => $y1, 'width' => $x2, 'height' => $y2); if ($template != 0) { $thumb_im = imagecrop($im, $to_crop_array); } else { $thumb_im = $im; } imagejpeg($thumb_im, $amountImgFileDirectory . $amountImgFileName, 100); //run OCR on the cropped section $tesseract = new TesseractOCR($amountImgFileDirectory . $amountImgFileName); $tesseract->setLanguage('eng'); $amount = $tesseract->recognize(); $amount = preg_replace("/[^0-9,.]/", "", $amount); $query3 = $this->templatedb->query("SELECT coordinateLabelX, coordinateLabelY, coordinateLabelX2, coordinateLabelY2 FROM datafields WHERE templateID = '" . $template . "' AND dataFieldLabel = 'duedate'"); $row = $query3->row(0); $x1 = $row->coordinateLabelX; $y1 = $row->coordinateLabelY; $x2 = $row->coordinateLabelX2 - $row->coordinateLabelX; $y2 = $row->coordinateLabelY2 - $row->coordinateLabelY; // Scale Up coordinates $x1 = $x1 * $width; $y1 = $y1 * $height; $x2 = $x2 * $width; $y2 = $y2 * $height; //cropping the image using the coordinate data $to_crop_array = array('x' => $x1, 'y' => $y1, 'width' => $x2, 'height' => $y2); if ($template != 0) { $thumb_im = imagecrop($im, $to_crop_array); } else { $thumb_im = $im; } imagejpeg($thumb_im, $dueDateImgFileDirectory . $dueDateImgFileName, 100); //run OCR on the cropped section $tesseract = new TesseractOCR($dueDateImgFileDirectory . $dueDateImgFileName); $tesseract->setLanguage('eng'); $duedate = $tesseract->recognize(); $amount = strtok($amount, " "); $day = strtok($duedate, " "); $month = strtok(" "); $year = strtok(" "); str_replace(array(",", "."), "", $day); str_replace(array(",", "."), "", $month); str_replace(array(",", "."), "", $year); if (ctype_alpha($day)) { $temp = $day; $day = $month; $month = $temp; } switch ($month) { case 'Jan': case 'January': $month = "01"; break; case 'Feb': case 'February': $month = "02"; break; case 'Mar': case 'March': $month = "03"; break; case 'Apr': case 'April': $month = "04"; break; case 'May': $month = "05"; break; case 'Jun': case 'June': $month = "06"; break; case 'Jul': case 'July': $month = "07"; break; case 'Aug': case 'August': $month = "08"; break; case 'Sep': case 'September': $month = "09"; break; case 'Oct': case 'October': $month = "10"; break; case 'Nov': case 'November': $month = "11"; break; case 'Dec': case 'December': $month = "12"; break; } $data = array('totalAmt' => $amount, 'billDueDate' => $year . "-" . $month . "-" . $day); $this->billdb->where('billID', $billID); $this->billdb->update('bills', $data); /* remove the cropped images once the check is complete. $command = escapeshellcmd('rm -f ' . $amountImgFileDirectory . $amountImgFileName); shell_exec($command); $command = escapeshellcmd('rm -f ' . $dueDateImgFileDirectory . $dueDateImgFileName); shell_exec($command); */ return $ini_filename; }
public function actionPhoto($id) { $model = $this->loadModel($id); $model->scenario = 'photo'; Yii::trace("FC.actionPhoto called", 'application.controllers.FamilyController'); if (Yii::app()->params['photoManip']) { if (isset($_POST['x1'])) { $x1 = $_POST['x1']; $y1 = $_POST['y1']; $width = $_POST['width']; $height = $_POST['height']; $pfile = $_POST['pfile']; $sdir = './images/uploaded/'; $size = getimagesize($sdir . $pfile); if ($size) { list($w, $h, $t) = $size; } else { Yii::trace("FR.actionPhoto crop call to getimagesize failed for image " . $sdir . $pfile . " returned {$size}", 'application.controllers.FamilyController'); } Yii::trace("FC.actionPhoto crop received {$x1}, {$y1}, {$width}, {$height}, {$w}, {$h}, {$t}", 'application.controllers.FamilyController'); switch ($t) { case 1: $img = imagecreatefromgif($sdir . $pfile); break; case 2: $img = imagecreatefromjpeg($sdir . $pfile); break; case 3: $img = imagecreatefrompng($sdir . $pfile); break; case IMAGETYPE_BMP: $img = ImageHelper::ImageCreateFromBMP($sdir . $pfile); break; case IMAGETYPE_WBMP: $img = imagecreatefromwbmp($sdir . $pfile); break; default: Yii::trace("FC.actionPhoto crop unknown image type {$t}", 'application.controllers.FamilyController'); } if (function_exists('imagecrop')) { # untested $cropped = imagecrop($img, array('x1' => $x1, 'y1' => $y1, 'width' => $width, 'height' => $height)); $scaled = imagescale($cropped, 400); } else { $h = $height * 400 / $width; $scaled = imagecreatetruecolor(400, $h); imagecopyresized($scaled, $img, 0, 0, $x1, $y1, 400, $h, $width, $height); } $dir = './images/families/'; $fname = preg_replace('/\\.[a-z]+$/i', '', $pfile); $fext = ".jpg"; if (file_exists($dir . $pfile)) { $fname .= "_01"; while (file_exists($dir . $fname . $fext)) { ++$fname; } } $dest = $dir . $fname . $fext; imagejpeg($scaled, $dest, 90); imagedestroy($scaled); imagedestroy($img); unlink($sdir . $pfile); $model->photo = $fname . $fext; $model->save(false); Yii::trace("FC.actionPhoto saved to {$pfile}", 'application.controllers.FamilyController'); $this->redirect(array('view', 'id' => $model->id)); return; } elseif (isset($_FILES['Families'])) { Yii::trace("FC.actionPhoto _FILES[Families] set", 'application.controllers.FamilyController'); $files = $_FILES['Families']; $filename = $files['name']['raw_photo']; if (isset($filename) and '' != $filename) { Yii::trace("FC.actionPhoto filename {$filename}", 'application.controllers.FamilyController'); $tmp_path = $files['tmp_name']['raw_photo']; if (isset($tmp_path) and '' != $tmp_path) { Yii::trace("FC.actionPhoto tmp_path {$tmp_path}", 'application.controllers.FamilyController'); $dir = "./images/uploaded/"; $dest = $dir . $filename; list($width, $height) = getimagesize($tmp_path); if ($width < 900) { $w = $width; $h = $height; $zoom = 1; } else { $w = 900; $h = $height * 900 / $width; $zoom = $w / $width; } $w = $width < 900 ? $width : 900; move_uploaded_file($tmp_path, $dest); $this->render('crop', array('model' => $model, 'pfile' => $filename, 'width' => $w, 'height' => $h, 'zoom' => $zoom)); return; } else { $errors = array(1 => "Size exceeds max_upload", 2 => "FORM_SIZE", 3 => "No tmp dir", 4 => "can't write", 5 => "error extension", 6 => "error partial"); $error = $errors[$files['error']['raw_photo']]; Yii::trace("FC.actionPhoto file error {$error}", 'application.controllers.FamilyController'); } } } } elseif (isset($_FILES['Families'])) { $files = $_FILES['Families']; $filename = $files['name']['photo']; if (isset($filename) and '' != $filename) { $tmp_path = $files['tmp_name']['photo']; if (isset($tmp_path) and '' != $tmp_path) { $dir = "./images/families/"; $fname = preg_replace('/\\.[a-z]+$/i', '', $filename); preg_match('/(\\.[a-z]+)$/i', $filename, $matches); $fext = $matches[0]; if (file_exists($dir . $filename)) { $fname .= "_01"; while (file_exists($dir . $fname . $fext)) { ++$fname; } } $dest = $dir . $fname . $fext; $model->photo = $fname . $fext; if ($model->save()) { move_uploaded_file($tmp_path, $dest); $this->redirect(array('view', 'id' => $model->id)); return; } } else { $model->addError('photo', $files['error']['photo']); } } } $this->render('photo', array('model' => $model)); }
public function upload(Request $request) { $data = $request->input('photo'); if ($data) { list($type, $data) = explode(';', $data); list(, $data) = explode(',', $data); $data = base64_decode($data); $meta = $request->input('meta'); $extension = explode('/', $meta['type'])[1]; $file = md5(microtime(true)) . '.' . $extension; $crop = $request->input('crop'); $src = imagecreatefromstring($data); if ($src = imagecrop($src, array('x' => $crop['x'], 'y' => $crop['y'], 'width' => $crop['width'], 'height' => $crop['height']))) { switch ($extension) { case 'jpg': case 'jpeg': imagejpeg($src, './uploads/' . $file); break; case 'gif': imagegif($src, './uploads/' . $file); break; case 'png': imagepng($src, './uploads/' . $file); break; } return json_encode(['file' => $file, 'url' => "http://{$_SERVER['HTTP_HOST']}/uploads/{$file}"]); } } return '上传失败'; }
function getTextFromImage($file) { $background = imagecreatefromjpeg('background.jpg'); $image = imagecreatefromstring($file); $black = imagecolorallocate($image, 0, 0, 0); $min_visible_y = $max_y = imagesy($image); $min_visible_x = $max_x = imagesx($image); $max_visible_x = $max_visible_y = 0; for ($y = 0; $y < $max_y; $y++) { for ($x = 0; $x < $max_x; $x++) { $pixel = ImageColorAt($image, $x, $y); $colors = imagecolorsforindex($image, $pixel); $pixel_bg = ImageColorAt($background, $x, $y); $colors_bg = imagecolorsforindex($background, $pixel_bg); $range = 35; if ($colors['red'] + $range > $colors_bg['red'] && $colors['red'] - $range < $colors_bg['red']) { imagesetpixel($image, $x, $y, $black); } else { $min_visible_x = $min_visible_x > $x ? $x : $min_visible_x; $max_visible_x = $max_visible_x < $x ? $x : $max_visible_x; $min_visible_y = $min_visible_y > $y ? $y : $min_visible_y; $max_visible_y = $max_visible_y < $y ? $y : $max_visible_y; } } } $image = imagecrop($image, ['x' => $min_visible_x, 'y' => $min_visible_y, 'width' => $max_visible_x, 'height' => $max_visible_y]); imagefilter($image, IMG_FILTER_GRAYSCALE); $tmpfname = tempnam("/tmp", "OCR"); imagepng($image, $tmpfname); $txt = $ocr->recognize($tmpfname, ['eng'], 3); unlink($tmpfname); return str_replace("\n", "", $txt); }
function image_crop($src_img, $filename, $final_path, $temp_file_path, $mime) { $to_crop_array = array('x' => 0, 'y' => 0, 'width' => 900, 'height' => 400); $new_image = imagecrop($src_img, $to_crop_array); $new_file_path = $final_path . $filename; unlink($temp_file_path); return $this->create_image($new_image, $new_file_path, $mime); }
function upload() { $idu = isset($_SESSION['idu']) ? $_SESSION['idu'] : 0; $this->stat->saveStat($idu, "photo/upload"); if ($idu > 0) { if (isset($_FILES['add-photo'])) { // var_dump($_FILES['add-photo']); $tmpFile = $_FILES['add-photo']['tmp_name']; $info = getimagesize($tmpFile); $width = $info[0]; $height = $info[1]; $mime = $info['mime']; if ($width != null && $height != null) { $md = md5(time()); $path = rtrim(LOCAL_DIR_PHOTO, '/\\') . '/'; $dir = $path . $idu . '/'; if (!is_dir($dir)) { mkdir($dir, 0777, true); } $fileName = $idu . '/' . $md . '.jpg'; $fileFullPath = $path . $fileName; if ($mime == 'image/jpeg') { $image = imagecreatefromjpeg($tmpFile); } if ($mime == 'image/png') { $image = imagecreatefrompng($tmpFile); } if (isset($image)) { $side = min($width, $height); $rect = array('x' => 0, 'y' => 0, 'width' => $side, 'height' => $side); $imageThumb = imagecreatetruecolor(PHOTO_SIZE, PHOTO_SIZE); $image = imagecrop($image, $rect); imagecopyresampled($imageThumb, $image, 0, 0, 0, 0, PHOTO_SIZE, PHOTO_SIZE, $side, $side); imagejpeg($imageThumb, $fileFullPath, 80); $model = new Model_Profile(); $model->uploadPhoto($idu, $fileName); imagedestroy($image); imagedestroy($imageThumb); } else { header('Location:' . WEB_APP . '/photo/'); return; } } else { header('Location:' . WEB_APP . '/photo/'); return; } } header('Location:' . WEB_APP . '/profile/'); } else { unset($_SESSION['idu']); header('Location:' . WEB_APP); } }
/** * Function to reduce code size in __async_edit method * @param resource $imageResource Image to crop * @return bool|resource Cropped image */ public function cropImage($imageResource) { /** @var int $imageTransparency Transparent color */ $imageTransparency = imagecolorallocatealpha($imageResource, 255, 255, 255, 127); /** @var resource $rotatedImage Rotated image resource */ $rotatedImage = imagerotate($imageResource, -$_POST['rotate'], $imageTransparency); /** @var resource $croppedImage Cropped image resource */ $croppedImage = imagecrop($rotatedImage, array('x' => $_POST['crop_x'], 'y' => $_POST['crop_y'], 'width' => $_POST['crop_width'], 'height' => $_POST['crop_height'])); // Delete temp image resource imagedestroy($rotatedImage); // Return cropped image return $croppedImage; }
public function crop($x, $y, $width, $height, $filename) { $cropArray = array('x' => $x, 'y' => $y, 'width' => $width, 'height' => $height); Debugger::debug($cropArray); $thumb_im = imagecrop($this->image, $cropArray); //$filename = PUBLIC_ROOT . $filename; if ($this->imageType == IMAGETYPE_JPEG) { imagejpeg($thumb_im, $filename, 100); } elseif ($this->imageType == IMAGETYPE_GIF) { imagegif($thumb_im, $filename); } elseif ($this->imageType == IMAGETYPE_PNG) { imagepng($thumb_im, $filename); } chmod($filename, 0777); }
/** * crop image * * @param string $imagePathname * @param string $prefix * @param array $selection * @return array */ protected function cropImage($imagePathname, $prefix, $selection) { // $destinationPath $destinationPath = public_path('resource\\' . $prefix); // checkImage and get type $type = $this->checkImage($imagePathname); // generate image name $imageName = $this->generateImageName($prefix, $type); // create image resource $imageResource = $this->createImageResource($imagePathname, $type); // crop image resource $imageCroppedResource = imagecrop($imageResource, $selection); // save image to destination imagejpeg($imageCroppedResource, "{$destinationPath}\\" . $imageName); // image url $imageUrl = url('resource/' . "{$prefix}/" . $imageName); return ['imgPathname' => $destinationPath . $imageName, 'imgUrl' => $imageUrl]; }
public function resizeImage($width, $height = 0, $crop = false) { $this->ImgNewHeight = $height; $this->ImgNewWidth = $width; $this->Crop = $crop; $this->calcSize(); $this->NewImgRes = imagecreatetruecolor($this->ImgResizeNewWidth, $this->ImgResizeNewHeight); // изменение размера if (imagecopyresampled($this->NewImgRes, $this->ImgRes, 0, 0, 0, 0, $this->ImgResizeNewWidth, $this->ImgResizeNewHeight, $this->ImgWidth, $this->ImgHeight)) { imagedestroy($this->ImgRes); $this->ImgRes = $this->NewImgRes; if ($crop) { $y = round($this->ImgResizeNewHeight / 2) - round($this->ImgNewHeight / 2); $this->ImgRes = imagecrop($this->ImgRes, array('x' => 0, 'y' => $y, 'width' => $this->ImgNewWidth, 'height' => $this->ImgNewHeight)); } $this->ImgWidth = $this->ImgNewWidth; $this->ImgHeight = $this->ImgNewHeight; } else { throw new \Exception('imagecopyresampled Error'); } }
/** * Resample image * @param $width * @param $height * @param $x * @param $y * @throws SPException * @return bool */ public function crop($width, $height, $x = 0, $y = 0) { // if ( !( function_exists( 'imagecrop' ) ) ) { // throw new SPException( 'Function "imagecrop" is not available on this server' ); // } if (!$this->_content) { $this->read(); } list($wOrg, $hOrg, $imgType) = getimagesize($this->_filename); $this->type = $imgType; $currentImg = $this->createImage($imgType); if (function_exists('imagecrop')) { $this->image = imagecrop($currentImg, array('x' => $x, 'y' => $y, 'width' => $width, 'height' => $height)); } else { // imagecopy ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h ) $this->image = imagecreatetruecolor($width, $height); imagecopy($this->image, $currentImg, 0, 0, $x, $y, $width, $height); } if ($imgType == IMAGETYPE_GIF || $imgType == IMAGETYPE_PNG) { $this->transparency($this->image); } $this->storeImage(); }
public function actionIndex() { $object = new ExampleModel(); if (Yii::$app->request->isPost) { // get post data $object->load(Yii::$app->request->post()); $object->file_attribute = UploadedFile::getInstance($object, 'file_attribute'); if ($object->validate()) { $object->save(); // lets get the image and crop it with the data passed via post from the form // this example is, for obvious reasons, only valid for jpeg image files. // This is already setted as a rule, so no sweat about it. $newimage = 'images/' . $object->file_attribute->baseName . '.' . $object->file_attribute->extension; $object->file_attribute->saveAs($newimage); $cropping_data = Yii::$app->request->post('file_attribute-cropping'); $im = imagecreatefromjpeg($newimage); $thumb_im = imagecrop($im, $cropping_data); imagejpeg($thumb_im, $newimage, 100); return 'File cropped successfully!'; } } else { return $this->render('index', ['object' => $object]); } }
//default } if (($iwidth == $avsize and $iheight <= $avsize) || ($iwidth <= $avsize and $iheight == $avsize)) { $userprefslib->set_user_avatar($userwatch, 'u', '', $name, $size, $itype, $data); } else { if (function_exists("ImageCreateFromString") && !strstr($type, "gif")) { $img = imagecreatefromstring($data); $size_x = imagesx($img); $size_y = imagesy($img); /* if the square crop is set, crop the image before resizing */ if ($prefs['user_small_avatar_square_crop']) { $crop_size = min($size_x, $size_y); $offset_x = ($size_x - $crop_size) / 2; $offset_y = ($size_y - $crop_size) / 2; $crop_array = array('x' => $offset_x, 'y' => $offset_y, 'width' => $crop_size, 'height' => $crop_size); $img = imagecrop($img, $crop_array); $size_x = $size_y = $crop_size; } if ($size_x > $size_y) { $tscale = (int) $size_x / $avsize; } else { $tscale = (int) $size_y / $avsize; } $tw = (int) ($size_x / $tscale); $ty = (int) ($size_y / $tscale); if ($tw > $size_x) { $tw = $size_x; } if ($ty > $size_y) { $ty = $size_y; }
/** * 裁剪图片到某个区域 * * @param int $x * @param int $y * @param int $w * @param int $h */ public function crop($x, $y, $w, $h) { if ($this->isEmpty()) { return $this; } $this->_img = imagecrop($this->img(), ['x' => $x, 'y' => $y, 'width' => $w, 'height' => $h]); return $this; }
function picture_crop($picture, $top = 0, $left = 0, $width = 0, $height = 0) { log_message('debug', 'Call picture_crop with crop : top : ' . $top . ' left : ' . $left . ' width : ' . $width . ' height : ' . $height . ''); if ($width == 0 || $height == 0) { return false; } //calculate thumb size $ow = imagesx($picture); $oh = imagesy($picture); log_message('debug', 'Call picture_crop : picture\'s dimensions : width : ' . $ow . ' height : ' . $oh . ''); if ($top + $height > $oh || $left + $width > $ow) { log_message('debug', 'Call picture_crop : returning no-crop for this picture'); return false; } log_message('debug', 'Call picture_crop : cropping in progress'); //resize and copy image return imagecrop($picture, array('x' => $left, 'y' => $top, 'width' => $width, 'height' => $height)); }
/** * @param int $width * @param int $height * @param int $offsetX * @param int $offsetY * * @return static */ public function crop($width, $height, $offsetX = 0, $offsetY = 0) { if (version_compare(PHP_VERSION, '5.5.0') < 0) { $image = imagecreatetruecolor($width, $height); imagealphablending($image, false); imagesavealpha($image, true); imagecopy($image, $this->_image, 0, 0, $offsetX, $offsetY, $width, $height); } else { $rect = ['x' => $offsetX, 'y' => $offsetY, 'width' => $width, 'height' => $height]; $image = imagecrop($this->_image, $rect); } imagedestroy($this->_image); $this->_image = $image; $this->_width = imagesx($image); $this->_height = imagesy($image); return $this; }
/** * Crops image via rectangle * * @param array $rectangle * @throws ImageException If couldn't crop image. */ public function crop(array $rectangle) { $croppedImage = @imagecrop($this->resource, $rectangle); if ($croppedImage === false) { $rectangleAsString = "{"; foreach ($rectangle as $key => $value) { $rectangleAsString .= "\"{$key}\" => {$value}, "; } $rectangleAsString = preg_replace("/, \$/", "}", $rectangleAsString); throw new ImageException("Can not crop image {$this} via rectangle {$rectangleAsString}.", ImageException::GenericException); } $this->resource = $croppedImage; $this->width = $rectangle["width"]; $this->height = $rectangle["height"]; }
/** * sets the avatar from a given image file's URL * * @return string URL for the current page */ function set_avatar_from_url($url, $userwatch = "", $name = "") { global $user, $prefs; $access = TikiLib::lib('access'); $access->check_feature('feature_userPreferences'); $access->check_user($user); $userprefslib = TikiLib::lib('userprefs'); $imagegallib = TikiLib::lib('imagegal'); if (empty($userwatch)) { $userwatch = $user; } $data = file_get_contents($url); list($iwidth, $iheight, $itype, $iattr) = getimagesize($url); $itype = image_type_to_mime_type($itype); // Get proper file size of image $imgdata = get_headers($url, true); if (isset($imgdata['Content-Length'])) { # Return file size $size = (int) $imgdata['Content-Length']; } // Store full-size file gallery image if that is required if ($prefs["user_store_file_gallery_picture"] == 'y') { $fgImageId = $userprefslib->set_file_gallery_image($userwatch, $name, $size, $itype, $data); } // Store small avatar if ($prefs['user_small_avatar_size']) { $avsize = $prefs['user_small_avatar_size']; } else { $avsize = "45"; //default } if (($iwidth == $avsize and $iheight <= $avsize) || ($iwidth <= $avsize and $iheight == $avsize)) { $userprefslib->set_user_avatar($userwatch, 'u', '', $name, $size, $itype, $data); } else { if (function_exists("ImageCreateFromString") && !strstr($type, "gif")) { $img = imagecreatefromstring($data); $size_x = imagesx($img); $size_y = imagesy($img); /* if the square crop is set, crop the image before resizing */ if ($prefs['user_small_avatar_square_crop']) { $crop_size = min($size_x, $size_y); $offset_x = ($size_x - $crop_size) / 2; $offset_y = ($size_y - $crop_size) / 2; $crop_array = array('x' => $offset_x, 'y' => $offset_y, 'width' => $crop_size, 'height' => $crop_size); $img = imagecrop($img, $crop_array); $size_x = $size_y = $crop_size; } if ($size_x > $size_y) { $tscale = (int) $size_x / $avsize; } else { $tscale = (int) $size_y / $avsize; } $tw = (int) ($size_x / $tscale); $ty = (int) ($size_y / $tscale); if ($tw > $size_x) { $tw = $size_x; } if ($ty > $size_y) { $ty = $size_y; } if (chkgd2()) { $t = imagecreatetruecolor($tw, $ty); imagecopyresampled($t, $img, 0, 0, 0, 0, $tw, $ty, $size_x, $size_y); } else { $t = imagecreate($tw, $ty); $imagegallib->ImageCopyResampleBicubic($t, $img, 0, 0, 0, 0, $tw, $ty, $size_x, $size_y); } // CHECK IF THIS TEMP IS WRITEABLE OR CHANGE THE PATH TO A WRITEABLE DIRECTORY $tmpfname = tempnam($prefs['tmpDir'], "TMPIMG"); imagejpeg($t, $tmpfname); // Now read the information $fp = fopen($tmpfname, "rb"); $t_data = fread($fp, filesize($tmpfname)); fclose($fp); unlink($tmpfname); $t_type = 'image/jpeg'; $userprefslib->set_user_avatar($userwatch, 'u', '', $name, $size, $t_type, $t_data); } else { $userprefslib->set_user_avatar($userwatch, 'u', '', $name, $size, $type, $data); } } TikiLib::events()->trigger('tiki.user.avatar', array('type' => 'user', 'object' => $userwatch, 'user' => $userwatch)); }
public function actionCropAvatar() { $uri = trim($_SERVER['REQUEST_URI'], '/'); $userId = User::checkLogged()['id']; $filePath = $_SERVER['DOCUMENT_ROOT'] . '/public/images/users/avatars/' . $userId . '.jpg'; if (!file_exists($filePath)) { $errors[] = 'Вы еще не загружали аватар'; } $result = false; if (isset($_POST["crop_image"])) { $errors = false; if (empty($_POST["x1"]) || empty($_POST["y1"]) || empty($_POST["w"]) || empty($_POST["h"])) { $errors[] = 'Вы не выбрали зону обрезки'; } if (!file_exists($filePath)) { $errors[] = 'Вы еще не загружали аватар'; } if ($errors == false) { $source = imagecreatefromjpeg($filePath); $x1 = $_POST["x1"]; $y1 = $_POST["y1"]; $w = $_POST["w"]; $h = $_POST["h"]; $cropped = imagecrop($source, array('x' => $x1, 'y' => $y1, 'width' => $w, 'height' => $h)); imagejpeg($cropped, $filePath); $result = true; } } require_once ROOT . '/views/user/crop_avatar.php'; }
private function createThumbs($image, $thumbWidth, $thumbHeight) { if (file_exists($image)) { // parse path for the extension $info = pathinfo($image); // continue only if this is a JPEG image if (strtolower($info['extension']) == 'jpg' && exif_imagetype($image) == IMAGETYPE_JPEG) { // load image and get image size $img = imagecreatefromjpeg($image); $width = imagesx($img); $height = imagesy($img); // calculate thumbnail size $new_width = $thumbWidth; $new_height = floor($height * ($thumbWidth / $width)); // create a new temporary image $tmp_img = imagecreatetruecolor($new_width, $new_height); // copy and resize old image into new image imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height); $to_crop_array = array('x' => 0, 'y' => 0, 'width' => $thumbWidth, 'height' => $thumbHeight); $thumb_im = imagecrop($tmp_img, $to_crop_array); // save thumbnail into a file imagejpeg($thumb_im, str_replace($this->dir_webscreenshots, $this->dir_thumbnails, $image)); } } }
/** * @param int $x * @param int $y * @param $width * @param $height */ public function crop($x = 0, $y = 0, $width, $height) { $this->copy = imagecrop($this->copy, array('x' => $x, 'y' => $y, 'width' => $width, 'height' => $height)); }
/** * Crops image. * @param mixed x-offset in pixels or percent * @param mixed y-offset in pixels or percent * @param mixed width in pixels or percent * @param mixed height in pixels or percent * @return self */ public function crop($left, $top, $width, $height) { list($r['x'], $r['y'], $r['width'], $r['height']) = static::calculateCutout($this->getWidth(), $this->getHeight(), $left, $top, $width, $height); if (PHP_VERSION_ID > 50611) { // PHP bug #67447 $this->image = imagecrop($this->image, $r); } else { $newImage = static::fromBlank($r['width'], $r['height'], self::RGB(0, 0, 0, 127))->getImageResource(); imagecopy($newImage, $this->image, 0, 0, $r['x'], $r['y'], $r['width'], $r['height']); $this->image = $newImage; } return $this; }
private function cropThumb($img, &$width, &$height, $thumb_width, $thumb_height) { $image_ratio = $height / $width; $thumb_ratio = $thumb_height / $thumb_width; if ($image_ratio !== $thumb_ratio) { if ($image_ratio < $thumb_ratio) { $new_width = $thumb_width * $height / $thumb_height; $square = ['x' => ($width - $new_width) / 2, 'y' => 0, 'width' => $new_width, 'height' => $height]; $width = $new_width; } else { if ($image_ratio > $thumb_ratio) { $new_height = $thumb_height * $width / $thumb_width; $square = ['x' => 0, 'y' => ($height - $new_height) / 2, 'width' => $width, 'height' => $new_height]; $height = $new_height; } } $img = imagecrop($img, $square); } return $img; }
} $data = base64_decode($newimgstring); $im = imagecreatefromstring($data); $actualwidth = imagesx($im); $actualheight = imagesy($im); $x1 = $actualwidth / 553 * $x1; $x2 = $actualwidth / 553 * $x2; $y1 = $actualheight / 553 * $y1; $y2 = $actualheight / 553 * $y2; if ($im !== false) { // ob_start(); // imagepng($im); // $contents = ob_get_contents(); // ob_end_clean(); $to_crop_array = array('x' => $x1, 'y' => $y1, 'width' => $x2, 'height' => $y2); $thumb_im = imagecrop($im, $to_crop_array); ob_start(); imagejpeg($thumb_im); $contents = ob_get_contents(); ob_end_clean(); $sql = "update profile SET profilephoto='data:image/jpeg;base64," . base64_encode($contents) . "' where profileid='{$profileid}'"; $result = mysqli_query($con, $sql); echo "<script>\ndocument.getElementById('prof-image').src = 'data:image/jpeg;base64," . base64_encode($contents) . "';\n\n\t </script>"; if (!$result) { die(mysqli_error($con)); } } } } ?> </div>
function cropImage($destination) { /* Crop */ $im; if (exif_imagetype($destination) == IMAGETYPE_JPEG) { $im = imagecreatefromjpeg($destination); } else { if (exif_imagetype($destination) == IMAGETYPE_PNG) { $im = imagecreatefrompng($destination); } else { return false; } } $ini_x_size = getimagesize($destination)[0]; $ini_y_size = getimagesize($destination)[1]; $crop_measure = min($ini_x_size, $ini_y_size); $px = 0; $py = 0; if ($ini_x_size > $ini_y_size) { $px = $ini_x_size / 2 - $crop_measure / 2; } else { $py = $ini_y_size / 2 - $crop_measure / 2; } $to_crop_array = array('x' => $px, 'y' => $py, 'width' => $crop_measure, 'height' => $crop_measure); $thumb_im = imagecrop($im, $to_crop_array); $ext = explode('.', $_FILES['file']['name']); $ext = $ext[count($ext) - 1]; $cropFile = basename($destination, "." . $ext); $cropFile = $cropFile . "_crop." . $ext; $cropFile = AVATAR_DIR . $cropFile; imagejpeg($thumb_im, $cropFile, 80); return $cropFile; }
private function make_thumb($src, $dest, $desired_width) { if (getimagesize($src)) { // read the source image $imgBlob = file_get_contents($src); $source_image = imagecreatefromstring($imgBlob); unset($imgBlob); $width = imagesx($source_image); $height = imagesy($source_image); //save crop data $cropSize = $desired_width; //min height - increase to crop if necessary $desired_height = ceil($height * ($desired_width / $width)); //check for min size if ($desired_height < $desired_width) { $ratio = $desired_width / $desired_height; $desired_height = $desired_width; $desired_width = ceil($ratio * $desired_height); } // create a new, "virtual" image $virtual_image = imagecreatetruecolor($desired_width, $desired_height); // copy source image at a resized size imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height); // crop $virtual_image = imagecrop($virtual_image, array('x' => 0, 'y' => 0, 'width' => $cropSize, 'height' => $cropSize)); // create the physical thumbnail image to its destination imagejpeg($virtual_image, $dest); } else { // get file extension $imgName = explode('.', $src); $extension = $imgName[count($imgName) - 1]; //if extension is PDF if ($extension == "pdf") { $src = $this->config->item('base_path') . $src; $dest = $this->config->item('base_path') . $dest; //$magick_dir $send_cmd = $this->config->item('magick_dir') . 'convert ' . $src . ' -resize 300x300 -gravity center -extent 300x300 ' . $dest; $result = exec($send_cmd, $out); } else { $src = 'assets/img/placeholders/' . $extension . '.png'; //safeguarg if (!file_exists($src)) { $src = 'assets/img/placeholders/placeholder.png'; } copy($src, $dest); } } }
$color = imagecolorallocate($img, $r, $g, $b); imagefilledrectangle($img, $x, $y + $i, $x1, $y + $i + 1, $color); } return true; } $im = imagecreate($_GET['width'], $_GET['height']); $bg = imagecolorallocate($im, 150, 150, 150); $black = imagecolorallocate($im, 0, 0, 0); image_gradientrect($im, 0, 0, $_GET['width'], $_GET['height'], 'FF0000', '0000FF'); for ($i = 0; $i <= $_GET['width']; $i += 100) { imageline($im, $i - 1, 0, $i - 1, $_GET['height'], $black); imageline($im, $i, 0, $i, $_GET['height'], $black); } for ($i = 0; $i <= $_GET['height']; $i += 100) { imageline($im, 0, $i - 1, $_GET['width'], $i - 1, $black); imageline($im, 0, $i, $_GET['width'], $i, $black); } for ($y = 0; $y <= $_GET['height']; $y += 100) { for ($x = 0; $x <= $_GET['width']; $x += 100) { $i = $y / 100; $j = $x / 100; imagestring($im, 3, $x + 6, $y + 2, "{$i}, {$j}", $textcolor); } } if (isset($_GET['crop'])) { list($cropX, $cropY, $cropWidth, $cropHeight) = explode(',', $_GET['crop']); $im = imagecrop($im, ['x' => $cropX, 'y' => $cropY, 'width' => $cropWidth, 'height' => $cropHeight]); } header("Content-type: image/png"); imagepng($im); imagedestroy($im);
/** * Apply transformations on image * * @param string $source Source image * @param array $params Transformations and parameters * @param string $store Temporary store on disk * * @return string */ public function transform($source, $params, $store = null) { $image = $this->_getImageAsResource($source); $result = null; if (isset($params['negate'])) { $res = imagefilter($image, IMG_FILTER_NEGATE); if ($res === false) { throw new \RuntimeException(_('Something went wrong in GD negate!')); } } if (isset($params['contrast'])) { $res = imagefilter($image, IMG_FILTER_CONTRAST, $params['contrast'] * -10); if ($res === false) { throw new \RuntimeException(_('Something went wrong in GD contrast!')); } } if (isset($params['brightness'])) { $res = imagefilter($image, IMG_FILTER_BRIGHTNESS, $params['brightness'] * 2.55); if ($res === false) { throw new \RuntimeException(_('Something went wrong in GD brightness!')); } } if (isset($params['rotate'])) { $result = imagerotate($result !== null ? $result : $image, 360 - $params['rotate']['angle'], 0); if ($result === null) { throw new \RuntimeException(_('Something went wrong in GD rotation!')); } } if (isset($params['crop'])) { $cparams = array('x' => $params['crop']['x'], 'y' => $params['crop']['y'], 'width' => $params['crop']['w'], 'height' => $params['crop']['h']); $infos = $this->getImageInfos($source); $orig_width = $infos[0]; $orig_height = $infos[1]; if (isset($params['rotate']) && ($params['rotate']['angle'] == 90 || $params['rotate']['angle'] == 270)) { $orig_width = $infos[1]; $orig_height = $infos[0]; } if ($orig_width < $cparams['width']) { $cparams['width'] = $orig_width; } if ($orig_height < $cparams['height']) { $cparams['height'] = $orig_height; } $result = imagecrop($result !== null ? $result : $image, $cparams); if ($result === null) { throw new \RuntimeException(_('Something went wrong in GD crop!')); } } if ($result === null) { $result = $image; } imagejpeg($result, $store); imagedestroy($result); }
/** * @param Char $char * @param array $size * @param array $cropData * @return resource */ private function generateColorFont(Char $char, $size, $cropData) { $image = imagecreatetruecolor($size['width'], $size['height']); $color = imagecolorallocate($image, $char->captchaColor['Red'][rand(0, 1)], $char->captchaColor['Green'][rand(0, 1)], $char->captchaColor['Blue'][rand(0, 1)]); $image = $this->transparentImage($image); $font = __DIR__ . '/../../Resources/Fonts/' . $char->captchaFont; imagettftext($image, $char->captchaSize, $char->captchaAngle, 20, $size['height'] / 2 + 20, $color, $font, $char->captchaChar); $img = imagecrop($image, $cropData); return $img; }
public function save($file_name) { if (file_exists($file_name)) { throw new \Exception("Save File Already Exists ({$file_name})"); } $to_crop = ['x' => $this->face['x'] - $this->padding_width / 2, 'y' => $this->face['y'] - $this->padding_height / 2, 'width' => $this->face['w'] + $this->padding_width, 'height' => $this->face['w'] + $this->padding_height]; $this->cropped_canvas = imagecrop($this->canvas, $to_crop); imagejpeg($this->cropped_canvas, $file_name, 100); }