public function pdfAction() { $model = $this->_processSvg(); $scale = $this->getRequest()->getPost('print_scale'); $model->addWhiteFontForPDF(); $data = $model->normalizeSvgData(); if ($model->getAdditionalData('order_increment_id')) { $filename = 'Order_' . $model->getAdditionalData('order_increment_id') . '_Image.pdf'; } else { $filename = 'Customer_Product_Image.pdf'; } $this->getResponse()->setHttpResponseCode(200)->setHeader('Pragma', 'public', true)->setHeader('Content-type', 'application/pdf', true)->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"', true); $this->getResponse()->clearBody(); //$this->getResponse()->setBody(str_replace('xlink:','',$data)); $imagick = new Imagick(); $imagick->readImageBlob($data); if ($scale != 1 && $scale <= 15) { $imagick->scaleImage($scale * $imagick->getImageWidth(), $scale * $imagick->getImageHeight()); } $imagick->setImageFormat("pdf"); /*$imagick->writeImage(MAGENTO_ROOT.'/media/us-map.pdf');scaleImage */ $this->getResponse()->setBody($imagick); $imagick->clear(); $imagick->destroy(); }
function programmatically_create_post() { $url = 'http://widgets.pinterest.com/v3/pidgets/boards/bradleyblose/my-stuff/pins/'; $json_O = json_decode(file_get_contents($url), true); $id = $json_O['data']['pins'][0]['id']; $titlelink = 'https://www.pinterest.com/pin/' . $id . '/'; $title = get_title($titlelink); var_dump($title); $original = $json_O['data']['pins'][0]['images']['237x']['url']; $image_url = preg_replace('/237x/', '736x', $original); $description = $json_O['data']['pins'][0]['description']; // Initialize the page ID to -1. This indicates no action has been taken. $post_id = -1; // Setup the author, slug, and title for the post $author_id = 1; $mytitle = get_page_by_title($title, OBJECT, 'post'); var_dump($mytitle); // If the page doesn't already exist, then create it if (NULL == get_page_by_title($title, OBJECT, 'post')) { // Set the post ID so that we know the post was created successfully $post_id = wp_insert_post(array('comment_status' => 'closed', 'ping_status' => 'closed', 'post_author' => $author_id, 'post_name' => $title, 'post_title' => $title, 'post_content' => $description, 'post_status' => 'publish', 'post_type' => 'post')); //upload featured image $upload_dir = wp_upload_dir(); $image_data = file_get_contents($image_url); $filename = basename($image_url); if (wp_mkdir_p($upload_dir['path'])) { $file = $upload_dir['path'] . '/' . $filename; $path = $upload_dir['path'] . '/'; } else { $file = $upload_dir['basedir'] . '/' . $filename; $path = $upload_dir['basedir'] . '/'; } file_put_contents($file, $image_data); //edit featured image to correct specs to fit theme $pngfilename = $filename . '.png'; $targetThumb = $path . '/' . $pngfilename; $img = new Imagick($file); $img->scaleImage(250, 250, true); $img->setImageBackgroundColor('None'); $w = $img->getImageWidth(); $h = $img->getImageHeight(); $img->extentImage(250, 250, ($w - 250) / 2, ($h - 250) / 2); $img->writeImage($targetThumb); unlink($file); //Attach featured image $wp_filetype = wp_check_filetype($pngfilename, null); $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($pngfilename), 'post_content' => '', 'post_status' => 'inherit'); $attach_id = wp_insert_attachment($attachment, $targetThumb, $post_id); require_once ABSPATH . 'wp-admin/includes/image.php'; $attach_data = wp_generate_attachment_metadata($attach_id, $targetThumb); wp_update_attachment_metadata($attach_id, $attach_data); set_post_thumbnail($post_id, $attach_id); // Otherwise, we'll stop } else { // Arbitrarily use -2 to indicate that the page with the title already exists $post_id = -2; } // end if }
public function index() { $ps = array(); $user = $this->session->all_userdata(); if (isset($_POST['submit']) && isset($user) && isset($user['users_id']) && isset($_FILES['uploaded_image']['tmp_name'])) { $imageFile = time() . '.' . end(explode(".", $_FILES['uploaded_image']['name'])); $photoData = $_POST['photo']; $image = new Imagick($_FILES['uploaded_image']['tmp_name']); $height = $image->getImageHeight(); $width = $image->getImageWidth(); if ($width > 800 || $height > 800) { if ($height < $width) { $image->scaleImage(800, 0); } else { $image->scaleImage(0, 600); } } $image->writeImage('./storage/photos/b/' . $imageFile); $image->cropThumbnailImage(100, 100); $image->writeImage('./storage/thumbs/' . $imageFile); $ps['photo_b'] = '/storage/photos/b/' . $imageFile; $ps['thumb'] = '/storage/thumbs/' . $imageFile; $data = array('iname' => $photoData['iname'] ? $photoData['iname'] : 'noname', 'idesc' => $photoData['idesc'] ? $photoData['idesc'] : '', 'path' => '/storage/photos/', 'file' => $imageFile, 'thumb' => $ps['thumb'], 'add_date' => time(), 'allow_comments' => isset($photoData['allow_comments']) ? 1 : 0, 'users_id' => $user['users_id']); $this->db->insert('photos', $data); $photos_id = $this->db->insert_id(); $this->load->model('m_users'); $this->load->model('m_logs'); $this->m_users->update(array('num_photos' => $user['num_photos'] + 1), $user['users_id']); $this->m_logs->add(array('users_id' => $user['users_id'], 'action' => 1, 'object_type' => 2, 'object_id' => $photos_id)); } $ps['_activeMenu'] = 'upload'; $this->tpl->view('frontend/upload/', $ps); }
/** * Resize the image. * @param integer $width * @param integer $height */ protected function _resize($width, $height) { if ($this->im->scaleImage($width, $height)) { $this->width = $this->im->getImageWidth(); $this->height = $this->im->getImageHeight(); } }
/** * @see AbstractImage::resize */ public function resize($iWidth = null, $iHeight = null) { //If null given, compute a valid size if (is_null($iWidth)) { $iWidth = $this->width * $iHeight / $this->height; } if (is_null($iHeight)) { $iHeight = $this->height * $iWidth / $this->width; } $this->resource->scaleImage($iWidth, $iHeight); $this->width = $iWidth; $this->height = $iHeight; }
/** * Crops Image. * * @since 3.5.0 * @access public * * @param int $src_x The start x position to crop from. * @param int $src_y The start y position to crop from. * @param int $src_w The width to crop. * @param int $src_h The height to crop. * @param int $dst_w Optional. The destination width. * @param int $dst_h Optional. The destination height. * @param bool $src_abs Optional. If the source crop points are absolute. * @return bool|WP_Error */ public function crop($src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false) { if ($src_abs) { $src_w -= $src_x; $src_h -= $src_y; } try { $this->image->cropImage($src_w, $src_h, $src_x, $src_y); $this->image->setImagePage($src_w, $src_h, 0, 0); if ($dst_w || $dst_h) { // If destination width/height isn't specified, use same as // width/height from source. if (!$dst_w) { $dst_w = $src_w; } if (!$dst_h) { $dst_h = $src_h; } $this->image->scaleImage($dst_w, $dst_h); return $this->update_size(); } } catch (Exception $e) { return new WP_Error('image_crop_error', $e->getMessage()); } return $this->update_size(); }
/** * {@inheritdoc} */ public function pixelate($pixelSize = 10) { $width = $this->image->getImageWidth(); $height = $this->image->getImageHeight(); $this->image->scaleImage((int) ($width / $pixelSize), (int) ($height / $pixelSize)); $this->image->scaleImage($width, $height); }
private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4, $format = "png", $quality = 85, $filename = FALSE, $save = TRUE, $print = false) { $imgH = count($frame); $imgW = strlen($frame[0]); $col[0] = new \ImagickPixel("white"); $col[1] = new \ImagickPixel("black"); $image = new \Imagick(); $image->newImage($imgW, $imgH, $col[0]); $image->setCompressionQuality($quality); $image->setImageFormat($format); $draw = new \ImagickDraw(); $draw->setFillColor($col[1]); for ($y = 0; $y < $imgH; $y++) { for ($x = 0; $x < $imgW; $x++) { if ($frame[$y][$x] == '1') { $draw->point($x, $y); } } } $image->drawImage($draw); $image->borderImage($col[0], $outerFrame, $outerFrame); $image->scaleImage(($imgW + 2 * $outerFrame) * $pixelPerPoint, 0); if ($save) { if ($filename === false) { throw new Exception("QR Code filename can't be empty"); } $image->writeImages($filename, true); } if ($print) { Header("Content-type: image/" . $format); echo $image; } }
/** * @param int $width * @param int $height * * @return static */ public function resize($width, $height) { $this->_image->scaleImage($width, $height); $this->_width = $this->_image->getImageWidth(); $this->_height = $this->_image->getImageHeight(); return $this; }
public function getAction($systemIdentifier, Request $request) { $width = $request->get('width'); $height = $request->get('height'); $system = $this->getDoctrine()->getRepository('KoalamonIncidentDashboardBundle:System')->findOneBy(['identifier' => $systemIdentifier, 'project' => $this->getProject()]); $webDir = $this->container->getParameter('assetic.write_to'); if ($system->getImage() == "") { $imageName = $webDir . self::DEFAULT_IMAGE; } else { $imageName = $webDir . ScreenshotCommand::IMAGE_DIR . DIRECTORY_SEPARATOR . $system->getImage(); } $image = new \Imagick($imageName); if ($height || $width) { if (!$height) { $ratio = $width / $image->getImageWidth(); $height = $image->getImageHeight() * $ratio; } if (!$width) { $ratio = $height / $image->getImageHeight(); $width = $image->getImageWidth() * $ratio; } $image->scaleImage($width, $height, true); } $headers = array('Content-Type' => 'image/png', 'Content-Disposition' => 'inline; filename="' . $imageName . '"'); return new Response($image->getImageBlob(), 200, $headers); }
function mkbilder($typ) { $this->err->write('mkbilder', $typ); $org = new Imagick(); if (!$org->readImage("/tmp/tmp.file_org")) { return false; } $big = new Imagick(); $big->newImage($this->bigwidth, $this->bigheight, new ImagickPixel('white')); $big->setImageFormat($typ); //$big->setImageColorspace($org->getImageColorspace() ); $big->setImageType(imagick::IMGTYPE_TRUECOLOR); $org->scaleImage($this->bigwidth, $this->bigheight, true); $d = $org->getImageGeometry(); $xoff = ($this->bigwidth - $d['width']) / 2; $big->compositeImage($org, imagick::COMPOSITE_DEFAULT, $xoff, 0); $rc = $big->writeImage("/tmp/tmp.file_org"); $big->clear(); $big->destroy(); $small = new Imagick(); $small->newImage($this->smallwidth, $this->smallheight, new ImagickPixel('white')); $small->setImageFormat($typ); //$small->setImageColorspace($org->getImageColorspace() ); $small->setImageType(imagick::IMGTYPE_TRUECOLOR); $org->scaleImage($this->smallwidth, $this->smallheight, true); $d = $org->getImageGeometry(); $xoff = ($this->smallwidth - $d['width']) / 2; $small->compositeImage($org, imagick::ALIGN_CENTER, $xoff, 0); $rc = $small->writeImage("/tmp/tmp.file_small"); $small->clear(); $small->destroy(); $org->clear(); $org->destroy(); return true; }
public function save() { $success = parent::save(); if ($success && isset($this->tempFile)) { $extension = $this->getExtension(); // save original $original = $this->name . "." . $extension; $path = $this->getPath(null, true); $this->logger->log("moving " . $this->tempFile["tmp_name"] . " to " . $path); $success = move_uploaded_file($this->tempFile["tmp_name"], $path); if ($success && $this->isImage()) { $thumbs = array(array('width' => 200, 'suffix' => 'small'), array('width' => 500, 'suffix' => 'med')); foreach ($thumbs as $thumb) { $thumb_path = $this->getPath($thumb['suffix'], true); $this->logger->log("thumbnailing " . $this->tempFile["tmp_name"] . " to " . $thumb_path); $image = new Imagick($path); $image->scaleImage($thumb['width'], 0); $image->writeImage($thumb_path); $image->destroy(); } } else { if (!$success) { $this->errorMessage = "Oops! We had trouble moving the file. Please try again later."; $success = false; } } } else { $this->status = "Sorry, there was an error with the file: " . $this->tempFile["error"]; $success = false; } return $success; }
public function scale($scale) { $width = ceil($this->width * $scale); $height = ceil($this->height * $scale); $this->image->scaleImage($width, $height, true); $this->updateSize($width, $height); return $this; }
/** * {@inheritdoc} */ public function scale(BoxInterface $size) { try { $this->imagick->scaleImage($size->getWidth(), $size->getHeight()); } catch (\ImagickException $e) { throw new RuntimeException('Scale operation failed', $e->getCode(), $e); } return $this; }
/** * @param \Imagick $imagick * @param int $graphWidth * @param int $graphHeight */ public static function analyzeImage(\Imagick $imagick, $graphWidth = 255, $graphHeight = 127) { $sampleHeight = 20; $border = 2; $imagick->transposeImage(); $imagick->scaleImage($graphWidth, $sampleHeight); $imageIterator = new \ImagickPixelIterator($imagick); $luminosityArray = []; foreach ($imageIterator as $row => $pixels) { /* Loop through pixel rows */ foreach ($pixels as $column => $pixel) { /* Loop through the pixels in the row (columns) */ /** @var $pixel \ImagickPixel */ if (false) { $color = $pixel->getColor(); $luminosityArray[] = $color['r']; } else { $hsl = $pixel->getHSL(); $luminosityArray[] = $hsl['luminosity']; } } /* Sync the iterator, this is important to do on each iteration */ $imageIterator->syncIterator(); break; } $draw = new \ImagickDraw(); $strokeColor = new \ImagickPixel('red'); $fillColor = new \ImagickPixel('red'); $draw->setStrokeColor($strokeColor); $draw->setFillColor($fillColor); $draw->setStrokeWidth(0); $draw->setFontSize(72); $draw->setStrokeAntiAlias(true); $previous = false; $x = 0; foreach ($luminosityArray as $luminosity) { $pos = $graphHeight - 1 - $luminosity * ($graphHeight - 1); if ($previous !== false) { /** @var $previous int */ //printf ( "%d, %d, %d, %d <br/>\n" , $x - 1, $previous, $x, $pos); $draw->line($x - 1, $previous, $x, $pos); } $x += 1; $previous = $pos; } $plot = new \Imagick(); $plot->newImage($graphWidth, $graphHeight, 'white'); $plot->drawImage($draw); $outputImage = new \Imagick(); $outputImage->newImage($graphWidth, $graphHeight + $sampleHeight, 'white'); $outputImage->compositeimage($plot, \Imagick::COMPOSITE_ATOP, 0, 0); $outputImage->compositeimage($imagick, \Imagick::COMPOSITE_ATOP, 0, $graphHeight); $outputImage->borderimage('black', $border, $border); $outputImage->setImageFormat("png"); App::cachingHeader("Content-Type: image/png"); echo $outputImage; }
public function testImageThumbnail() { var_dump("123 Inside Image Thumbnail"); $thumb = new \Imagick('/home/vagrant/www/consult-api/app/myimage.jpg'); $thumb->scaleImage(200, 200, 1); $thumb->writeImage('/home/vagrant/www/consult-api/app/mythumb.jpg'); $thumb->clear(); $thumb->destroy(); }
public function start() { $data['_activeMenu'] = 'admin'; ignore_user_abort(true); set_time_limit(0); $offset = 0; $limit = 10; $this->db->where('updated', 0); $this->db->where('is_deleted', 0); $query = $this->db->get('photos_il', $limit, $offset); $photos = $query->result_array(); while (count($photos) > 0) { foreach ($photos as $p) { $img = $p['img']; $imageFile = str_replace('http://photo.ilich.in.ua/upload/', '', $img); echo '<p>' . $imageFile . '</p>'; if (file_exists('./upload/' . $imageFile)) { $image = new Imagick('./upload/' . $imageFile); //$imageFile=time().'.'.end(explode(".", $_FILES['uploaded_image']['name'])); $height = $image->getImageHeight(); $width = $image->getImageWidth(); if ($width > 800 || $height > 800) { if ($height < $width) { $image->scaleImage(800, 0); } else { $image->scaleImage(0, 600); } } $image->writeImage('./storage_2/photos/b/' . $imageFile); $image->cropThumbnailImage(100, 100); $image->writeImage('./storage_2/thumbs/' . $imageFile); $this->db->where('phid', $p['phid']); $this->db->update('photos_il', array('updated' => 1)); } else { $this->db->where('phid', $p['phid']); $this->db->update('photos_il', array('is_deleted' => 1)); } } $this->db->where('updated', 0); $query = $this->db->get('photos_il', $limit, $offset); $photos = $query->result_array(); } //$this->tpl->view('backend/install/', $data); }
function createMedium($url, $filename, $width, $height) { # Function creates a smaller version of a photo when its size is bigger than a preset size # Excepts the following: # (string) $url = Path to the photo-file # (string) $filename = Name of the photo-file # (int) $width = Width of the photo # (int) $height = Height of the photo # Returns the following # (boolean) true = Success # (boolean) false = Failure # Set to true when creation of medium-photo failed global $settings; $error = false; # Size of the medium-photo # When changing these values, # also change the size detection in the front-end global $newWidth; global $newHeight; # Check permissions if (hasPermissions(LYCHEE_UPLOADS_MEDIUM) === false) { # Permissions are missing $error = true; echo 'Not enough persmission on the medium folder' . "\n"; } # Is photo big enough? # Is Imagick installed and activated? if ($error === false && ($width > $newWidth || $height > $newHeight) && (extension_loaded('imagick') && $settings['imagick'] === '1')) { $newUrl = LYCHEE_UPLOADS_MEDIUM . $filename; # Read image $medium = new Imagick(); $medium->readImage(LYCHEE . $url); # Adjust image $medium->scaleImage($newWidth, $newHeight, true); # Save image try { $medium->writeImage($newUrl); } catch (ImagickException $err) { Log::notice($database, __METHOD__, __LINE__, 'Could not save medium-photo: ' . $err->getMessage()); $error = true; echo 'Imagick Exception:' . "\n"; var_dump($e); } $medium->clear(); $medium->destroy(); } else { # Photo too small or # Imagick not installed $error = true; } if ($error === true) { return false; } return true; }
/** * Создание тамбнейла: */ private static function createThumbnail($path, $name) { $thumb = new Imagick($path); $width = $thumb->getImageWidth(); $height = $thumb->getImageHeight(); $s = self::scaleImage($width, $height, 150, 200); $thumb->scaleImage($s[0], $s[1]); $thumb->writeImage($name); $thumb->destroy(); return true; }
/** * Generate and save scales images with specified width and height * * @param int $width The width to resize the image with * @param int $height The height to resize the image with */ private function generateResizedImages(int $width, int $height) { $this->image->scaleImage($width, $height); if ($width === 0) { $width = $this->image->getImageWidth(); } if ($height === 0) { $height = $this->image->getImageHeight(); } $this->image->writeImage($this->imageSavePath . DIRECTORY_SEPARATOR . $this->imageName . '_' . $width . 'x' . $height . '.' . $this->imageExtension); }
/** * Get Thumbnail Response * * @param integer $width * @param Image $image * * @return Response */ public function getThumbnailResponse($width, $image) { if (!$image instanceof Image) { throw new \LogicException("Not a valid image"); } $core = explode(";", $image->getContent()); $content = base64_decode(substr($core[1], 7)); $thumbnail = new \Imagick(); $thumbnail->readImageBlob($content); $thumbnail->scaleImage($width, 0); return new Response($thumbnail->getImageBlob(), 200, array('Content-Type' => $image->getMimeType())); }
public function resize($width = 0, $height = 0, $scaled = true, $color = 'FFFFFF') { if (!$this->info['width'] || !$this->info['height']) { return; } $rgb = $this->html2rgb($color); $xpos = 0; $ypos = 0; $scale = min($width / $this->info['width'], $height / $this->info['height']); if ($scale == 1) { return; } if ($scaled) { $new_width = round($this->info['width'] * $scale); $new_height = round($this->info['height'] * $scale); $xpos = round(($width - $new_width) / 2); $ypos = round(($height - $new_height) / 2); } else { $new_width = $width; $new_height = $height; } $canvas = new Imagick(); $canvas->newImage($width, $height, new ImagickPixel('rgba(' . $rgb[0] . ',' . $rgb[1] . ',' . $rgb[2] . ',0)')); list($extension) = explode('?', $this->info['extension']); $canvas->setImageFormat($extension); for ($r = 0; $r < count($this->image); $r++) { $this->image->scaleImage($new_width, $new_height); $this->image->nextImage(); $canvas->compositeImage($this->image, $this->image->getImageCompose(), $xpos, $ypos); } $this->image = $canvas; //$canvas->clear(); //$canvas->destroy(); $this->info['width'] = $width; $this->info['height'] = $height; }
public function scale($scale) { $width = ceil($this->width * $scale); $height = ceil($this->height * $scale); if ($this->multiframe()) { $this->image = $this->image->coalesceImages(); foreach ($this->image as $frame) { $frame->scaleImage($width, $height, true); $frame->setImagePage($width, $height, 0, 0); } } else { $this->image->scaleImage($width, $height, true); } $this->update_size($width, $height); return $this; }
function submit_photo() { $dir = "../images"; $pid = intval(get_http_var('pid')); $errors = array(); if (!array_key_exists('photo', $_FILES)) { array_push($errors, 'Not got the photo.'); } elseif ($_FILES['photo']['error'] > 0) { array_push($errors, 'There was an error uploading the photo.'); } elseif (!is_uploaded_file($_FILES['photo']['tmp_name'])) { array_push($errors, 'Did not get an uploaded file.'); } else { $tmp_name = $_FILES['photo']['tmp_name']; $image = new Imagick(); $image->readImage($tmp_name); if (!$image) { array_push($errors, 'Failed to read image from uploaded file'); } $imageS = clone $image; if (!$image->scaleImage(0, 118)) { array_push($errors, 'Scaling large failed'); } if (!$imageS->scaleImage(0, 59)) { array_push($errors, 'Scaling small failed'); } if (!$image->writeImage("{$dir}/mpsL/{$pid}.jpeg")) { array_push($errors, "Saving to {$dir}/mpsL/{$pid}.jpeg failed"); } if (!$imageS->writeImage("{$dir}/mps/{$pid}.jpeg")) { array_push($errors, "Saving to {$dir}/mps/{$pid}.jpeg failed"); } if (!$errors) { print "<pre>"; chdir($dir); passthru('git pull'); passthru("git add mpsL/{$pid}.jpeg"); passthru("git add mps/{$pid}.jpeg"); passthru('git commit -m "Photo update from admin web photo upload interface."'); passthru('git push'); print "</pre>"; } } if ($errors) { return display_photo_form($errors); } return "<p><em>Photo uploaded and resized for pid {$pid}</em> — check how it looks <a href=\"/mp?p={$pid}\">on their page</a></p>" . display_photo_form(); }
public function wp_generate_attachment_metadata($data) { global $_wp_additional_image_sizes; $upload_dir = wp_upload_dir()['basedir'] . '/'; foreach ($_wp_additional_image_sizes as $k => $size) { if (array_key_exists('padded', $size) && $size['padded']) { // Check the image has an incorrect aspect ratio list($width, $height) = getimagesize($orig_file = $upload_dir . $data['file']); if (round($size['height'] * $width / $height) == $size['width']) { continue; } // Scale image down $im = new Imagick($orig_file); $im->setImageFormat('png'); $im->scaleImage($size['width'], $size['height'], true); // Get new width & height $width = $im->getImageWidth(); $height = $im->getImageHeight(); // Save temporary version $im->writeImage($orig_file . '.tmp'); $im->clear(); $im->destroy(); // Create the padded version $im = imagecreatetruecolor($size['width'], $size['height']); imagesavealpha($im, true); imagefill($im, 0, 0, imagecolorallocatealpha($im, 0, 0, 0, 127)); imagecopy($im, $tmp = imagecreatefrompng($orig_file . '.tmp'), round(($size['width'] - $width) / 2), round(($size['height'] - $height) / 2), 0, 0, $width, $height); imagedestroy($tmp); imagepng($im, $file = $upload_dir . dirname($data['file']) . '/' . ($filename = basename($data['file'], '.' . pathinfo($data['file'])['extension']) . '-' . $size['width'] . 'x' . $size['height'] . '.png')); imagedestroy($im); // Destroy the temporary version unlink($orig_file . '.tmp'); // Update metadata if (!array_key_exists($k, $data['sizes'])) { $data['sizes'][$k] = []; } $data['sizes'][$k]['file'] = $filename; $data['sizes'][$k]['height'] = $size['height']; $data['sizes'][$k]['mime-type'] = 'image/png'; $data['sizes'][$k]['width'] = $size['width']; } } return $data; }
public function createThumbnail($rawdata, $sw, $sh, $path) { // イメージ読み込み $image = new Imagick(); $image->readImageBlob($rawdata); $iw = $image->getImageWidth(); $ih = $image->getImageHeight(); // リサイズなし if ($sw == $iw && $sh == $ih) { // ファイル書き込み $fh = fopen($path, 'wb'); fwrite($fh, $image->getImagesBlob()); fclose($fh); } elseif ($sw / $iw > $sh / $ih) { $ww = intval($iw * $sh / $ih); $hh = intval($ih * $sw / $iw); $image->scaleImage($sw, $hh); // 重ね合わせ $im2 = new Imagick(); $im2->newImage($sw, $sh, "none"); $im2->compositeImage($image, Imagick::COMPOSITE_DEFAULT, 0, intval(($sh - $hh) / 2)); //$im2->compositeImage($image, Imagick::COMPOSITE_DEFAULT, 0, 0); $im2->setImageFormat('jpeg'); // ファイル書き込み $fh = fopen($path, 'wb'); fwrite($fh, $im2->getImagesBlob()); fclose($fh); } else { $ww = intval($iw * $sh / $ih); $hh = intval($ih * $sw / $iw); $image->scaleImage($ww, $sh); // 重ね合わせ $im2 = new Imagick(); $im2->newImage($sw, $sh, "none"); $im2->compositeImage($image, Imagick::COMPOSITE_DEFAULT, intval(($sw - $ww) / 2), 0); //$im2->compositeImage($image, Imagick::COMPOSITE_DEFAULT, 0, 0); $im2->setImageFormat('jpeg'); // ファイル書き込み $fh = fopen($path, 'wb'); fwrite($fh, $im2->getImagesBlob()); fclose($fh); } }
function generateQRCode($hash) { $link = Config::HOST . Config::BASE_URI . 'gallery/' . $hash; $imageBlob = (new Endroid\QrCode\QrCode())->setText($link)->setPadding(7)->setErrorCorrection('high')->get(); $qrcode = new Imagick(); $qrcode->readImageBlob($imageBlob); $qrcode->scaleImage(600, 600, true); $camera = new Imagick(__DIR__ . '/camera.png'); $qrcodeSize = $qrcode->getImageGeometry(); $cameraSize = $camera->getImageGeometry(); $qrcode->compositeImage($camera, Imagick::COMPOSITE_DEFAULT, round(($qrcodeSize['width'] - $cameraSize['width']) / 2), round(($qrcodeSize['height'] - $cameraSize['height']) / 2)); $qrcode->setImageFormat('png'); header('Content-Type: image/png'); echo $qrcode->getImageBlob(); $qrcode->clear(); $qrcode->destroy(); $camera->clear(); $camera->destroy(); exit; }
/** * Prepare the image for output, scaling and flattening as required * * @since 2.10 * @uses self::$image updates the image in this Imagick object * * @param integer zero or new width * @param integer zero or new height * @param boolean proportional fit (true) or exact fit (false) * @param string output MIME type * @param integer compression quality; 1 - 100 * * @return void */ private static function _prepare_image($width, $height, $best_fit, $type, $quality) { if (is_callable(array(self::$image, 'scaleImage'))) { if (0 < $width && 0 < $height) { // Both are set; use them as-is self::$image->scaleImage($width, $height, $best_fit); } elseif (0 < $width || 0 < $height) { // One is set; scale the other one proportionally if reducing $image_size = self::$image->getImageGeometry(); if ($width && isset($image_size['width']) && $width < $image_size['width']) { self::$image->scaleImage($width, 0); } elseif ($height && isset($image_size['height']) && $height < $image_size['height']) { self::$image->scaleImage(0, $height); } } else { // Neither is specified, apply defaults self::$image->scaleImage(150, 0); } } if (0 < $quality && 101 > $quality) { if ('image/jpeg' == $type) { self::$image->setImageCompressionQuality($quality); self::$image->setImageCompression(imagick::COMPRESSION_JPEG); } else { self::$image->setImageCompressionQuality($quality); } } if ('image/jpeg' == $type) { if (is_callable(array(self::$image, 'setImageBackgroundColor'))) { self::$image->setImageBackgroundColor('white'); } if (is_callable(array(self::$image, 'mergeImageLayers'))) { self::$image = self::$image->mergeImageLayers(imagick::LAYERMETHOD_FLATTEN); } elseif (is_callable(array(self::$image, 'flattenImages'))) { self::$image = self::$image->flattenImages(); } } }
private function make_thumbnail_Imagick($src_path, $width, $height, $dest) { $image = new Imagick($src_path); # Select the first frame to handle animated images properly if (is_callable(array($image, 'setIteratorIndex'))) { $image->setIteratorIndex(0); } // устанавливаем качество $format = $image->getImageFormat(); if ($format == 'JPEG' || $format == 'JPG') { $image->setImageCompression(Imagick::COMPRESSION_JPEG); } $image->setImageCompressionQuality(85); $h = $image->getImageHeight(); $w = $image->getImageWidth(); // если не указана одна из сторон задаем ей пропорциональное значение if (!$width) { $width = round($w * ($height / $h)); } if (!$height) { $height = round($h * ($width / $w)); } list($dx, $dy, $wsrc, $hsrc) = $this->crop_coordinates($height, $h, $width, $w); // обрезаем оригинал $image->cropImage($wsrc, $hsrc, $dx, $dy); $image->setImagePage($wsrc, $hsrc, 0, 0); // Strip out unneeded meta data $image->stripImage(); // уменьшаем под размер $image->scaleImage($width, $height); $image->writeImage($dest); chmod($dest, 0755); $image->clear(); $image->destroy(); return true; }
} else { $page = new Page(); } $page->slug = $slug; $page->title = Input::get('title'); $page->summary = Input::get('summary'); $page->content = Input::get('content'); $page->publish = Input::get('publish'); $page->save(); return Redirect::to('admin/pages'); }), 'POST /admin/newmedia' => array('before' => 'auth', function () { $imagename = time() . Input::file('image.name'); File::upload('image', PUBLIC_PATH . 'img/' . $imagename); $newimage = PUBLIC_PATH . 'img/' . $imagename; $image = new Imagick($newimage); $image->scaleImage(400, 0); $image->writeImage(PUBLIC_PATH . 'img/medium_' . $imagename); $image->resizeImage(80, 80, Imagick::FILTER_LANCZOS, 1, TRUE); $image->writeImage(PUBLIC_PATH . 'img/thumb_' . $imagename); $image->destroy(); $media = new Media(); $media->filename = $imagename; $media->caption = Input::get('caption'); $media->meta = Input::get('meta'); $media->save(); return Redirect::to('admin/media'); }), 'POST /admin/newuser' => array('before' => 'auth', function () { $rules = array('firstname' => 'required|max:140', 'lastname' => 'required|max:140', 'email' => 'required|max:50|unique:users', 'role' => 'required', 'password' => 'required|max:50|between:6,16|confirmed'); $validator = Validator::make(Input::get(), $rules); if (!$validator->valid()) { return Redirect::to('admin/newuser')->with('errors', $validator->errors)->with_input('except', array('password', 'password_confirmation'));