/**
  * @param $data
  * @return ImageWorkshopLayer
  *
  * @throws \PHPImageWorkshop\Exception\ImageWorkshopException
  */
 protected function initFromDataWithTempFile($data)
 {
     $tempFile = tempnam(sys_get_temp_dir(), 'img');
     $handle = fopen($tempFile, 'w+');
     fwrite($handle, $data);
     return ImageWorkshop::initFromPath($tempFile);
 }
Exemple #2
0
 private function watermark($data = array())
 {
     $this->load->library('files/files');
     $mark_text = isset($data['text']) ? $data['text'] : Settings::get('site_name');
     $font_color = isset($data['font_color']) ? $data['font_color'] : 'ffffff';
     $opacity = isset($data['opacity']) ? (int) $data['opacity'] : 100;
     $font_size = isset($data['font_size']) ? (int) $data['font_size'] : 12;
     $files = $data['files'];
     $font_path = './' . SHARED_ADDONPATH . 'modules/watermark/fonts/Gabrielle.ttf';
     if (is_array($files) && count($files) > 0) {
         foreach ($files as $file) {
             $filedata = Files::get_file($file);
             if ($filedata['status'] === TRUE) {
                 $dirpath = FCPATH . '/uploads/default/files/';
                 $source = $dirpath . $filedata['data']->filename;
                 $imageLayer = ImageWorkshop::initFromPath($source);
                 //var_dump($imageLayer);exit;
                 $textLayer = ImageWorkshop::initTextLayer($mark_text, $font_path, $font_size, $font_color, $data['rotation']);
                 $textLayer->opacity($opacity);
                 $imageLayer->addLayerOnTop($textLayer, 12, 12, $data['position']);
                 $image = $imageLayer->getResult();
                 $imageLayer->save($dirpath, $filedata['data']->filename, false, null, 100);
                 $wm_data = array('file_id' => $filedata['data']->id, 'folder_id' => $filedata['data']->folder_id);
                 $this->watermark_m->insert($wm_data);
             }
         }
         $this->session->set_flashdata('success', lang('watermark:submit_success'));
         redirect('admin/watermark');
     } else {
         $this->session->set_flashdata('error', lang('watermark:no_files_remaining'));
         redirect('admin/watermark');
     }
 }
 public function generateAction(Application $app, Request $req, $arguments)
 {
     $expectedWidth = $arguments['width'];
     $expectedHeight = $arguments['height'];
     $largestSide = max($expectedWidth, $expectedHeight);
     $base = ImageWorkshop::initFromPath($arguments['file']);
     $base->cropMaximumInPixel(0, 0, "MM");
     $base->resizeInPixel($largestSide, $largestSide);
     $base->cropInPixel($expectedWidth, $expectedHeight, 0, 0, 'MM');
     $fileName = basename($arguments['file']);
     if (!$arguments['on_the_fly']) {
         $folder = $arguments['web_root'] . $arguments['mount'] . '/' . $arguments['width'] . 'x' . $arguments['height'];
         $base->save($folder, $fileName, true);
         $arguments['logger'](Logger::DEBUG, "File saved in '{$folder}/{$fileName}'");
     }
     $ext = strtolower(pathinfo($arguments['file'], PATHINFO_EXTENSION));
     if ($ext == 'jpg') {
         $ext = 'jpeg';
     }
     $mimeType = 'image/' . $ext;
     $func = 'image' . $ext;
     if (!function_exists($func)) {
         $arguments['logger'](Logger::CRITICAL, "How this possible?");
         $app->abort(404);
     }
     //I don't know any way to pass an image resource to symfony Response object.
     ob_start();
     $func($base->getResult());
     $result = ob_get_clean();
     return new Response($result, 200, array('Content-Type' => $mimeType, 'Content-Disposition' => 'filename="' . $fileName . '"'));
 }
function smamo_filter_image()
{
    $response = array();
    // Masser af logik om filstier mv.
    // Hvis du kigger for længe på det, brænder dine øjne ud af hovedet, så pas på!
    // Vi skal dybest set bare bruge filens navn og dens placering og den slags.
    // Vi skal kunne skifte mellem basedir og baseurl, fordi det er vigtigt.
    // huskeregel: "baseurl" er en sti på internettet, "basedir" er en sti lokalt på serveren
    // Dvs. "baseurl til javascript", "basedir" til PHP
    /* SWEET HEAVENS, HERE GOES */
    $upload_dir = wp_upload_dir();
    $imgPath = wp_strip_all_tags($_POST['img']);
    $file = explode('?', basename($imgPath));
    $file = $file[0];
    $imgPath = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $imgPath);
    if (file_exists($upload_dir['basedir'] . '/filtered/' . $file)) {
        $response['img'] = $upload_dir['baseurl'] . '/filtered/' . $file;
        $response['exist'] = true;
    } else {
        require_once get_template_directory() . '/PHPImageWorkshop/ImageWorkshop.php';
        /* OPRET BILLEDE FRA FIL */
        $image = ImageWorkshop::initFromPath($imgPath);
        /* KLON, FILTRER, LÆG OVENPÅ */
        $gray = clone $image;
        $gray->applyFilter(IMG_FILTER_CONTRAST, -35, null, null, null, true);
        // Kontrast
        $gray->applyFilter(IMG_FILTER_GRAYSCALE);
        // Gråtone
        $gray->applyFilter(IMG_FILTER_COLORIZE, 0, 43, 127, 80);
        // Kolorisering, cirka blålig
        $gray->opacity(40);
        // Gennemsigtighed
        $image->addLayerOnTop($gray, 0, 0, "LT");
        // Læg ovenpå original
        /* TILFØJ RIDSER */
        // Først skal vi vælge en ridse, baseret på billedets størrelse
        $imageWidth = $image->getWidth();
        $gunk = 'noise-4.png';
        if ($imageWidth > 800) {
            $gunk = 'noise-1.png';
        }
        if ($imageWidth > 600) {
            $gunk = 'noise-3.png';
        }
        if ($imageWidth > 400) {
            $gunk = 'noise-2.png';
        }
        $noise = ImageWorkshop::initFromPath($upload_dir['basedir'] . '/filtered/colors/' . $gunk);
        // Så bestemmer vi tilfældigt hvor ridsen placeres
        $filterpos = array('LT', 'RT', 'LB', 'RB');
        $pos = $filterpos[array_rand($filterpos)];
        // Og lægger ovenpå
        $image->addLayerOnTop($noise, 0, 0, $pos);
        /* GEM BILLEDE, TILFØJ STI TIL RESPONSE */
        $image->save($upload_dir['basedir'] . '/filtered/', $file, true, null, 100);
        $response['img'] = $upload_dir['baseurl'] . '/filtered/' . $file;
        $response['exist'] = false;
    }
    wp_die(json_encode($response));
}
 public function postSubirfondo(Request $request, $id)
 {
     if (!$request->hasFile('file')) {
         return response()->json(['error' => 'No hay ningun archivo'], 400);
     }
     list($contenido, $file) = [Contenido::findOrFail($id), $request->file('file')];
     if (empty($mensaje = $this->validarArchivo($contenido, $file))) {
         list($atributos_tip_pub) = [$contenido->tipoPublicaciones->getAttributes()];
         $fileName = $contenido->tipoPublicaciones->getAttributes()['descripcion'] . $contenido->id . "." . $file->getClientOriginalExtension();
         $base_path = 'archivos' . '/' . 'contenidos' . '/' . $contenido->tipoPublicaciones->getAttributes()['descripcion'];
         $file->move($base_path, $fileName);
         $foto = ImageWorkshop::initFromPath($base_path . '/' . $fileName);
         //            $foto->cropMaximumInPixel(0, 0, "MM");
         //            $foto->resizeInPixel(160, 160);
         $foto->save($base_path, $fileName);
         if ($contenido->fondo != "") {
             File::delete($base_path . $contenido->fondo);
         }
         $contenido->fondo = $fileName;
         $contenido->save();
         return response()->json(['url' => url($base_path . '/' . $fileName), 'mensaje' => "Datos guardados correctamente"], 200);
     } else {
         return response()->json($mensaje, 400);
     }
 }
Exemple #6
0
 public function upload($fileInput, $prefix = "user_", $options = null)
 {
     $uploadObj = new Upload();
     if ($options == null) {
         $directory = PATH_FILES . "users";
         $fileName = $uploadObj->UploadFile($fileInput, $directory, array("task" => "rename"), $prefix);
         //resize
         $path = PATH_FILES . "users/" . $fileName;
         $layer = ImageWorkshop::initFromPath($path);
         $layer->cropMaximumInPixel(0, 0, "MM");
         $layer->resizeInPixel(160, 160, true);
         $layer->save(PATH_FILES . "users/thumb", $fileName, true);
     }
     if ($options["task"] == "book") {
         $directory = PATH_FILES . "books";
         $fileName = $uploadObj->UploadFile($fileInput, $directory, array("task" => "rename"), $prefix);
         //resize
         $path = PATH_FILES . "books/" . $fileName;
         $layer = ImageWorkshop::initFromPath($path);
         $layer->resizeInPixel(140, 210, true);
         $layer->save(PATH_FILES . "books/thumb/140x210", $fileName, true);
         $layer->resizeInPixel(210, 280, true);
         $layer->save(PATH_FILES . "books/thumb/210x280", $fileName, true);
         $layer->resizeInPixel(80, 120, true);
         $layer->save(PATH_FILES . "books/thumb/80x120", $fileName, true);
     }
     if ($options["task"] == "slider") {
         $directory = PATH_FILES . "sliders";
         $fileName = $uploadObj->UploadFile($fileInput, $directory, array("task" => "rename"), $prefix);
     }
     return $fileName;
 }
 /**
  * @param string    $image
  * @param int       $width
  * @param int       $height
  *
  * @throws \PHPImageWorkshop\Exception\ImageWorkshopException
  */
 public function __construct($image, $width, $height)
 {
     // Initialize layer from existing image
     $layer = ImageWorkshop::initFromPath($image);
     // Resize picture to be squared
     $layer->resizeInPixel($width, $height);
     // Get width and height of resized image
     $width = $layer->getWidth();
     $height = $layer->getHeight();
     // Make save configuration parameters
     $saveConfig = new SaveConfig($image, $width, $height, __CLASS__);
     $config = $saveConfig->getConfiguration();
     // Save resized image
     $layer->save($config['saveLocation'], $config['fileName'], $config['createFolder'], $config['backgroundColor'], $config['imageQuality']);
 }
 /**
  * @param string    $image
  * @param int       $xlen
  * @param int       $ylen
  * @param int       $xpos
  * @param int       $ypos
  * @param string    $pointerPosition
  *
  * @throws \PHPImageWorkshop\Exception\ImageWorkshopException
  */
 public function __construct($image, $xlen, $ylen, $xpos = 0, $ypos = 0, $pointerPosition = 'LB')
 {
     // Initialize layer from existing image
     $layer = ImageWorkshop::initFromPath($image);
     // Crop image based on given dimensions
     $layer->cropInPixel($xlen, $ylen, $xpos, $ypos, $pointerPosition);
     // Get width and height of resized image
     $width = $layer->getWidth();
     $height = $layer->getHeight();
     // Make save configuration parameters
     $saveConfig = new SaveConfig($image, $width, $height, __CLASS__);
     $config = $saveConfig->getConfiguration();
     // Save resized image
     $layer->save($config['saveLocation'], $config['fileName'], $config['createFolder'], $config['backgroundColor'], $config['imageQuality']);
 }
Exemple #9
0
 /**
  * Resizes an image
  *
  * @param string $file Full file path
  * @param int    $width   Maximum width
  * @param int    $height  Maximum height
  * @param int    $quality Quality ratio
  */
 private function resize($file, $width = null, $height = null, $quality = 90)
 {
     if ($width || $height) {
         $finalWidth = $width;
         $finalHeight = $height;
         $crop = $width && $height;
         $iw = ImageWorkshop::initFromPath($file);
         if ($crop) {
             $originalRatio = $iw->getWidth() / $iw->getHeight();
             $finalRatio = $finalWidth / $finalHeight;
             if ($originalRatio > $finalRatio) {
                 $width = null;
             } else {
                 $height = null;
             }
         }
         $iw->resizeInPixel($width, $height, true, 0, 0, 'MM');
         $crop && $iw->cropInPixel($finalWidth, $finalHeight, 0, 0, 'MM');
         $iw->save(dirname($file), basename($file), false, null, $quality);
     }
 }
Exemple #10
0
 public static function uploadImageWorkshop($file_path = '', $file = '', $uploadInfo)
 {
     $file_name = self::fileNameNew($file);
     $file_path_nods = rtrim($file_path, DS);
     if (!is_dir($file_path_nods)) {
         mkdir($file_path_nods, 0777, true);
     }
     if (move_uploaded_file($file['tmp_name'], $file_path . $file_name)) {
         if (!empty($uploadInfo)) {
             foreach ($uploadInfo as $key => $row) {
                 $layer = ImageWorkshop::initFromPath($file_path . $file_name);
                 $key = rtrim($key, '/');
                 $layer->resizeInPixel($row['width'], $row['height'], true, 0, 0, 'MM');
                 $layer->save($file_path . $key, $file_name);
             }
             $layer->delete();
         }
         return $file_name;
     } else {
         return false;
     }
 }
 private function getBackground()
 {
     // create image
     $layer = ImageWorkshop::initFromPath($this->background_tmp);
     // resize
     //$newLargestSideWidth = self::WIDTH; // %
     //$conserveProportion = true;
     $layer->resizeInPixel(null, self::HEIGHT, true);
     // We can ignore the other params ($positionX, $positionY, $position)
     //$layer->resizeByNarrowSideInPixel($newLargestSideWidth, $conserveProportion);
     // crop
     //$layer->cropMaximumInPercent(0, 0, 'MM');
     $createFolders = false;
     $backgroundColor = null;
     // transparent, only for PNG (otherwise it will be white if set null)
     $imageQuality = 70;
     // useless for GIF, usefull for PNG and JPEG (0 to 100%)
     $layer->save("/tmp/", $this->background_tmp_gif, $createFolders, $backgroundColor, $imageQuality);
     $file_name = null;
     if (file_exists($this->background_tmp)) {
         $file_name = $this->background_tmp;
     }
     return $file_name;
 }
 /**
  * Summary.
  *
  * @since  0.9.0
  * @see
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  * @param \Silex\Application                        $app
  *
  * @return JsonResponse
  * @author nguyenvanduocit
  */
 public function generate(Request $request, Application $app)
 {
     $backgroundId = $request->get('backgroundId');
     $resultObject = new AttachmentResponse();
     if (array_key_exists($backgroundId, $this->memeList)) {
         $text = $request->get('text');
         $meme = $this->memeList[$backgroundId];
         $fileName = md5(mt_rand(1, 20)) . '.jpg';
         $mainLayer = ImageWorkshop::initFromPath($meme['src']);
         $textPaths = explode(';', $text);
         foreach ($textPaths as $index => $text) {
             if (array_key_exists($index, $meme['position'])) {
                 $position = $meme['position'][$index];
             } else {
                 $lastPostion = count($meme['position']) - 1;
                 $position = $meme['position'][$lastPostion];
             }
             $textLayer = ImageWorkshop::initTextLayer($text, APP_DIR . '/Asset/font/OpenSans-Bold.ttf', $meme['font']['size'], $meme['font']['color'], 0, null);
             if ($textLayer->getWidth() >= $mainLayer->getWidth()) {
                 $textLayer->resizeInPixel($mainLayer->getWidth() - 100, NULL, TRUE);
             }
             if ($position === 'top') {
                 $y = 0 + 20;
             } else {
                 $y = $mainLayer->getHeight() - $textLayer->getHeight() - 20;
             }
             $x = $mainLayer->getWidth() / 2 - $textLayer->getWidth() / 2;
             $mainLayer->addLayer($index, $textLayer, $x, $y);
         }
         $mainLayer->save($this->outputDir, $fileName);
         $resultObject->setImageUrl('http://slackbotapi.senviet.org/web/public/meme/' . $fileName . '?rand=' . uniqid('rand', FALSE));
     } else {
         $resultObject->setImageUrl('http://slackbotapi.senviet.org/web/public/meme/list.jpg');
     }
     return new JsonResponse($resultObject);
 }
Exemple #13
0
     if ($layerWidth > $mainLayerWidth) {
         $layerWidth = $col_x * $watermarkWidth;
     }
 }
 if ($offsetTop < 0) {
     $maxWM_y = 2 * intval($mainLayerHeight / ($watermarkHeight - $wmMarginBottom));
     $unseenWM_y = intval(abs($offsetTop) / $watermarkHeight);
     $offsetTop = $offsetTop + $unseenWM_y * $watermarkHeight;
     $col_y = ceil((abs($coooffsetToprdy) + $mainLayerHeight) / $watermarkHeight);
     $layerHeight = $watermarkHeight * ($maxWM_y - $unseenWM_y);
     if ($layerHeight > $mainLayerHeight) {
         $layerHeight = $col_y * $watermarkHeight;
     }
 }
 $layer = ImageWorkshop::initVirginLayer($mainLayerWidth, $mainLayerHeight);
 $row = ImageWorkshop::initVirginLayer($mainLayerWidth, $watermarkHeight);
 $tile_x = 0;
 $tile_y = 0;
 $x = 0;
 $y = 0;
 while ($x++ < $col_x) {
     $row->addLayer(1, $watermark, $tile_x, 0, "LT");
     $row->mergeAll();
     $tile_x += $watermarkWidth;
 }
 while ($y++ < $col_y) {
     $layer->addLayer(1, $row, 0, $tile_y, "LT");
     $layer->mergeAll();
     $tile_y += $watermarkHeight;
 }
 $watermark = clone $layer;
 /**
  * Crop the document.
  *
  * $backgroundColor can be set transparent (but script could be long to execute)
  * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html
  *
  * @param string $unit
  * @param mixed  $width     (integer or float)
  * @param mixed  $height    (integer or float)
  * @param mixed  $positionX (integer or float)
  * @param mixed  $positionY (integer or float)
  * @param string $position
  */
 public function crop($unit = self::UNIT_PIXEL, $width = 0, $height = 0, $positionX = 0, $positionY = 0, $position = 'LT')
 {
     if ($width < 0 || $height < 0) {
         throw new ImageWorkshopLayerException('You can\'t use negative $width or $height for "' . __METHOD__ . '" method.', static::ERROR_NEGATIVE_NUMBER_USED);
     }
     if ($unit == self::UNIT_PERCENT) {
         $width = round($width / 100 * $this->width);
         $height = round($height / 100 * $this->height);
         $positionX = round($positionX / 100 * $this->width);
         $positionY = round($positionY / 100 * $this->height);
     }
     if ($width != $this->width || $positionX == 0 || ($height != $this->height || $positionY == 0)) {
         if ($width == 0) {
             $width = 1;
         }
         if ($height == 0) {
             $height = 1;
         }
         $layerTmp = ImageWorkshop::initVirginLayer($width, $height);
         $layerClone = ImageWorkshop::initVirginLayer($this->width, $this->height);
         imagedestroy($layerClone->image);
         $layerClone->image = $this->image;
         $layerTmp->addLayer(1, $layerClone, -$positionX, -$positionY, $position);
         $newPos = $layerTmp->getLayerPositions();
         $layerNewPosX = $newPos[1]['x'];
         $layerNewPosY = $newPos[1]['y'];
         // update the layer
         $this->width = $layerTmp->getWidth();
         $this->height = $layerTmp->getHeight();
         $this->image = $layerTmp->getResult();
         unset($layerTmp);
         unset($layerClone);
         $this->updateLayerPositionsAfterCropping($layerNewPosX, $layerNewPosY);
     }
 }
 /**
  * Setup the layer and its width & height
  * NB: The image must contain the full path
  * @param $image
  * @return \PHPImageWorkshop\Core\ImageWorkshopLayer|string
  * @throws \PHPImageWorkshop\Exception\ImageWorkshopException
  */
 public function setImage($image)
 {
     $this->layer = \PHPImageWorkshop\ImageWorkshop::initFromPath($image);
     $this->setWidthAndHeight();
 }
 /**
  * Test initFromString
  */
 public function testInitFromString()
 {
     $layer = ImageWorkshop::initFromString(file_get_contents(__DIR__ . static::IMAGE_SAMPLE_PATH));
     $this->assertTrue(is_object($layer) === true, 'Expect $layer to be an object');
     $this->assertTrue(get_class($layer) === 'PHPImageWorkshop\\Core\\ImageWorkshopLayer', 'Expect $layer to be an ImageWorkshopLayer object');
 }
Exemple #17
0
 /**
  * Crop the document
  *
  * $backgroundColor can be set transparent (but script could be long to execute)
  * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html
  *
  * @param string $unit
  * @param float $width
  * @param float $height
  * @param float $positionX
  * @param float $positionY
  * @param string $position
  */
 public function crop($unit = self::UNIT_PIXEL, $width = 0, $height = 0, $positionX = 0, $positionY = 0, $position = 'LT')
 {
     if ($unit == self::UNIT_PERCENT) {
         $width = round($width / 100 * $this->width);
         $height = round($height / 100 * $this->height);
         $positionX = round($positionX / 100 * $this->width);
         $positionY = round($positionY / 100 * $this->height);
     }
     if ($width != $this->width || $positionX == 0 || ($height != $this->height || $positionY == 0)) {
         $layerTmp = ImageWorkshop::initVirginLayer($width, $height);
         $layerClone = ImageWorkshop::initVirginLayer($this->width, $this->height);
         imagedestroy($layerClone->image);
         $layerClone->image = $this->image;
         $layerTmp->addLayer(1, $layerClone, -$positionX, -$positionY, $position);
         $newPos = $layerTmp->getLayerPositions();
         $layerNewPosX = $newPos[1]['x'];
         $layerNewPosY = $newPos[1]['y'];
         // update the layer
         $this->width = $layerTmp->getWidth();
         $this->height = $layerTmp->getHeight();
         $this->image = $layerTmp->getResult();
         unset($layerTmp);
         unset($layerClone);
         $this->updateLayerPositionsAfterCropping($layerNewPosX, $layerNewPosY);
     }
 }
 /**
  * Initialize a layer
  * 
  * @param integer $method
  */
 protected function initializeLayer($method = 1)
 {
     $layer = ImageWorkshop::initVirginLayer(100, 75);
     switch ($method) {
         case 1:
             break;
         case 2:
             // Add 4 sublayers in $layer stack
             $layer->addLayer(1, $layer);
             $layer->addLayer(2, $layer);
             $layer->addLayer(3, $layer);
             $layer->addLayer(4, $layer);
             break;
         case 3:
             // Add 5 sublayers in $layer stack
             $layer->addLayer(1, $layer);
             $layer->addLayer(2, $layer);
             $layer->addLayer(3, $layer);
             $layer->addLayer(4, $layer);
             $layer->addLayer(5, $layer);
             break;
     }
     return $layer;
 }
Exemple #19
0
 protected function createThumbnail()
 {
     $image = ImageWorkshop::initFromPath($this->getUploadRootDir() . '/' . $this->path);
     $image->resizeInPixel(self::THUMBNAIL_WIDTH, self::THUMBNAIL_HEIGHT, true);
     $image->save($this->getUploadRootDir() . '/thumbnail/', $this->path, true, null, 80);
 }
     $route = '/model/' . $parent["model_class"];
     \runner::redirect_route($route, \runner::config("scaffold"), true, $_model_context, $router, $parent_model);
     if (is_array($parent_model) && count($parent_model) == 1) {
         $parent_model = array_shift($parent_model);
     }
     if (isset($parent_model) && is_object($parent_model) && get_parent_class($parent_model) == "Routerunner\\BaseModel" && isset($parent_model->label)) {
         $path_route .= \runner::toAscii($parent_model->label) . DIRECTORY_SEPARATOR;
     }
     $debug = 1;
 }
 if (isset($value["src"])) {
     // crop image
     $src = $_SESSION["runner_config"]['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . $_SESSION["runner_config"]["SITEROOT"] . $value["src"];
     $filename = substr($value["src"], strrpos($value["src"], DIRECTORY_SEPARATOR) + 1);
     $mimetype = false;
     $layer = ImageWorkshop::initFromPath($src, false, $mimetype);
     if (isset($value["rotate"])) {
         $layer->rotate($value["rotate"]);
     } elseif (isset($value["angle"])) {
         $layer->rotate($value["angle"]);
     }
     if ($crops) {
         $layers = array();
         unset($crops[$field]);
         foreach ($crops as $size => $crop_data) {
             $layers[$size] = clone $layer;
             $crop_field = str_replace("data_", "", $size);
             $crop_data["id"] = $model->table_id;
             $crop_data[$size] = array("src" => $value["src"], "angle" => $value["angle"]);
             $width = isset($crop_data["width"]) ? $crop_data["width"] : null;
             $height = isset($crop_data["height"]) ? $crop_data["height"] : null;
 public function cropPicture($uid, $crop = null, $ext = 'jpg')
 {
     //如果不裁剪,则发生错误
     if (!$crop) {
         $this->error('必须裁剪');
     }
     $path = "/Uploads/Avatar/" . $uid . "/original." . $ext;
     //获取文件路径
     $fullPath = substr($path, 0, 1) == '/' ? '.' . $path : $path;
     $savePath = str_replace('original', 'crop', $fullPath);
     $returnPath = str_replace('original', 'crop', $path);
     $returnPath = substr($returnPath, 0, 1) == '/' ? '.' . $returnPath : $returnPath;
     //解析crop参数
     $crop = explode(',', $crop);
     $x = $crop[0];
     $y = $crop[1];
     $width = $crop[2];
     $height = $crop[3];
     //是sae则不需要获取全路径
     if (strtolower(C('PICTURE_UPLOAD_DRIVER')) == 'local') {
         //本地环境
         $image = ImageWorkshop::initFromPath($fullPath);
         //生成将单位换算成为像素
         $x = $x * $image->getWidth();
         $y = $y * $image->getHeight();
         $width = $width * $image->getWidth();
         $height = $height * $image->getHeight();
         //如果宽度和高度近似相等,则令宽和高一样
         if (abs($height - $width) < $height * 0.01) {
             $height = min($height, $width);
             $width = $height;
         }
         //调用组件裁剪头像
         $image = ImageWorkshop::initFromPath($fullPath);
         $image->crop(ImageWorkshopLayer::UNIT_PIXEL, $width, $height, $x, $y);
         $image->save(dirname($savePath), basename($savePath));
         //返回新文件的路径
         return $returnPath;
     } elseif (strtolower(C('PICTURE_UPLOAD_DRIVER')) == 'sae') {
         //sae
         //载入临时头像
         $f = new \SaeFetchurl();
         $img_data = $f->fetch($fullPath);
         $img = new \SaeImage();
         $img->setData($img_data);
         $img_attr = $img->getImageAttr();
         //生成将单位换算成为像素
         $x = $x * $img_attr[0];
         $y = $y * $img_attr[1];
         $width = $width * $img_attr[0];
         $height = $height * $img_attr[1];
         //如果宽度和高度近似相等,则令宽和高一样
         if (abs($height - $width) < $height * 0.01) {
             $height = min($height, $width);
             $width = $height;
         }
         $img->crop($x / $img_attr[0], ($x + $width) / $img_attr[0], $y / $img_attr[1], ($y + $height) / $img_attr[1]);
         $new_data = $img->exec();
         $storage = new \SaeStorage();
         $thumbFilePath = str_replace(C('UPLOAD_SAE_CONFIG.rootPath'), '', dirname($savePath) . '/' . basename($savePath));
         $thumbed = $storage->write(C('UPLOAD_SAE_CONFIG.domain'), $thumbFilePath, $new_data);
         //返回新文件的路径
         return $thumbed;
     } elseif (strtolower(C('PICTURE_UPLOAD_DRIVER')) == 'qiniu') {
         $imageInfo = file_get_contents($fullPath . '?imageInfo');
         $imageInfo = json_decode($imageInfo);
         //生成将单位换算成为像素
         $x = $x * $imageInfo->width;
         $y = $y * $imageInfo->height;
         $width = $width * $imageInfo->width;
         $height = $height * $imageInfo->height;
         $new_img = $fullPath . '?imageMogr2/crop/!' . $width . 'x' . $height . 'a' . $x . 'a' . $y;
         //返回新文件的路径
         return $new_img;
     }
 }
Exemple #22
0
<?php

ini_set("memory_limit", "256M");
require_once '../PHPImageWorkshop/ImageWorkshop.php';
use PHPImageWorkshop\ImageWorkshop;
$x_coordinates = $_POST['x-original'];
$y_coordinates = $_POST['y-original'];
$slider_opacity = $_POST['opacity'] * 100;
$main_image_input = $_POST['url_img'];
$watermark_input = $_POST['url_watermark'];
$tile_mode = $_POST['array'];
$tile_mode = explode(",", $tile_mode);
$main_image = ImageWorkshop::initFromPath($main_image_input);
$watermark = ImageWorkshop::initFromPath($watermark_input);
$watermark->opacity($slider_opacity);
list($watermark_width, $watermark_height) = getimagesize($watermark_input);
list($img_width, $img_height) = getimagesize($main_image_input);
$margin_x = $_POST['x-coordinates'];
$margin_y = $_POST['y-coordinates'];
/*
есть инпут с именем array
в нем список значений через запятую
0 - индикатор замощения
1 - координата y
2 - координата x
3 - столбци
4 - строки
*/
$y_coordinates_tiles = $tile_mode[1];
$x_coordinates_tiles = $tile_mode[2];
if ($tile_mode[0] === 'true') {
Exemple #23
0
 private function cropAvatar($path, $crop = null)
 {
     //如果不裁剪,则发生错误
     if (!$crop) {
         $this->error = '必须裁剪';
         return false;
     }
     //是sae则不需要获取全路径
     if (strtolower(APP_MODE) != 'sae') {
         //本地环境
         //获取头像的文件路径
         $fullPath = $this->getFullPath($path);
         //生成文件名后缀
         $postfix = substr(md5($crop), 0, 8);
         $savePath = preg_replace('/\\.[a-zA-Z0-9]*$/', '-' . $postfix . '$0', $fullPath);
         $returnPath = preg_replace('/\\.[a-zA-Z0-9]*$/', '-' . $postfix . '$0', $path);
         //解析crop参数
         $crop = explode(',', $crop);
         $x = $crop[0];
         $y = $crop[1];
         $width = $crop[2];
         $height = $crop[3];
         //载入临时头像
         $image = ImageWorkshop::initFromPath($fullPath);
         //如果宽度和高度近似相等,则令宽和高一样
         if (abs($height - $width) < $height * 0.01) {
             $height = min($height, $width);
             $width = $height;
         } else {
             $this->error = $height . '图像必须为正方形';
             return false;
         }
         //确认头像足够大
         if ($height < 256) {
             $this->error = '头像太小';
             return false;
         }
         //调用组件裁剪头像
         $image = ImageWorkshop::initFromPath($fullPath);
         $image->crop(ImageWorkshopLayer::UNIT_PIXEL, $width, $height, $x, $y);
         $image->save(dirname($savePath), basename($savePath));
         //返回新文件的路径
         return $returnPath;
     } else {
         //sae
         $fullPath = $path;
         $postfix = substr(md5($crop), 0, 8);
         $savePath = preg_replace('/\\.[a-zA-Z0-9]*$/', '-' . $postfix . '$0', $fullPath);
         $returnPath = preg_replace('/\\.[a-zA-Z0-9]*$/', '-' . $postfix . '$0', $path);
         //解析crop参数
         $crop = explode(',', $crop);
         $x = $crop[0];
         $y = $crop[1];
         $width = $crop[2];
         $height = $crop[3];
         //载入临时头像
         $f = new \SaeFetchurl();
         $img_data = $f->fetch($fullPath);
         $img = new \SaeImage();
         $img->setData($img_data);
         $img_attr = $img->getImageAttr();
         //生成将单位换算成为像素
         $x = $x * $img_attr[0];
         $y = $y * $img_attr[1];
         $width = $width * $img_attr[0];
         $height = $height * $img_attr[1];
         //如果宽度和高度近似相等,则令宽和高一样
         if (abs($height - $width) < $height * 0.01) {
             $height = min($height, $width);
             $width = $height;
         } else {
             $this->error = '图像必须为正方形';
             return false;
         }
         //确认头像足够大
         if ($height < 128) {
             $this->error = '头像太小';
             return false;
         }
         /*       dump('x='.$x);
                  dump('y='.$y);
                  dump('w='.$width);
                  dump('h='.$height);exit;*/
         $img->crop($x / $img_attr[0], ($x + $width) / $img_attr[0], $y / $img_attr[1], ($y + $height) / $img_attr[1]);
         $new_data = $img->exec();
         $storage = new \SaeStorage();
         $thumbFilePath = str_replace(C('UPLOAD_SAE_CONFIG.rootPath'), '', dirname($savePath) . '/' . basename($savePath));
         $thumbed = $storage->write(C('UPLOAD_SAE_CONFIG.domain'), $thumbFilePath, $new_data);
         //返回新文件的路径
         return $thumbed;
     }
 }
    echo $dirout;
}
/*$posx = filter_input(INPUT_POST, 'coordx');
$posy = filter_input(INPUT_POST, 'coordy');
$padx = filter_input(INPUT_POST, 'marginx');
$pady = filter_input(INPUT_POST, 'marginy');
$opacity = filter_input(INPUT_POST, 'opacity') * 100;*/
$posx = filter_input(INPUT_POST, 'posx');
$posy = filter_input(INPUT_POST, 'posy');
$margx = filter_input(INPUT_POST, 'margx');
$margy = filter_input(INPUT_POST, 'margy');
$opacity = filter_input(INPUT_POST, 'opacity') * 100;
//$mode = filter_input(INPUT_POST, 'mode'); // tile or not
// открываем картинки
$mainpic = ImageWorkshop::initFromPath(__DIR__ . $img_main_path);
$wtmpic = ImageWorkshop::initFromPath(__DIR__ . $img_watmark_path);
// параметры файлов
$main_width = $mainpic->getWidth();
$main_height = $mainpic->getHeight();
$wtm_width = $wtmpic->getWidth();
$wtm_height = $wtmpic->getHeight();
// прибавляем отступы к ватермарку
$wmpic_width += $margx;
$wmpic_height += $margy;
$wtmpic->opacity($opacity);
$mainpic->addLayerOnTop($wtmpic, $posx, $posy);
// Saving the result
$dirPath = __DIR__ . $dirout;
$createFolders = true;
$backgroundColor = null;
// transparent, only for PNG (otherwise it will be white if set null)
 /**
  * Process image types here and returns filename to write
  *
  * @param array $aFile uploaded file information
  * @param string $folder the file path
  * @param string $aName the file name
  * @param array $imageInfo image information array: width, height, resize_mode
  *
  * @return bool|string
  * @throws ImageWorkshopException
  * @throws Exception
  */
 public function processImage($aFile, $folder, $aName, $imageInfo)
 {
     $ext = self::_getImageExt($aFile['type']);
     if (empty($ext)) {
         $this->setMessage(iaLanguage::getf('file_type_error', array('extension' => implode(', ', array_unique(self::$_typesMap)))));
         return false;
     }
     try {
         $path = IA_UPLOADS . $folder;
         $image = ImageWorkshop::initFromPath($aFile['tmp_name']);
         // save source image
         $image->save($path, self::SOURCE_PREFIX . $aName . $ext);
         // process thumbnails for files uploaded in CKEditor and other tools
         if (empty($imageInfo)) {
             // apply watermark
             $image = self::_applyWaterMark($image);
             $image->save($path, self::_createFilename($aName, $ext));
             return true;
         }
         // check this is an animated GIF
         if (self::ALLOW_ANIMATED_GIFS && 'image/gif' == $aFile['type']) {
             require_once IA_INCLUDES . 'phpimageworkshop' . IA_DS . 'Core' . IA_DS . 'GifFrameExtractor.php';
             $gifPath = $aFile['tmp_name'];
             if (GifFrameExtractor\GifFrameExtractor::isAnimatedGif($gifPath)) {
                 // Extractions of the GIF frames and their durations
                 $gfe = new GifFrameExtractor\GifFrameExtractor();
                 $frames = $gfe->extract($gifPath);
                 // For each frame, we add a watermark and we resize it
                 $retouchedFrames = array();
                 $thumbFrames = array();
                 foreach ($frames as $frame) {
                     $frameLayer = ImageWorkshop::initFromResourceVar($frame['image']);
                     $thumbLayer = ImageWorkshop::initFromResourceVar($frame['image']);
                     $frameLayer->resizeInPixel($imageInfo['image_width'], $imageInfo['image_height'], true);
                     $frameLayer = self::_applyWaterMark($frameLayer);
                     $retouchedFrames[] = $frameLayer->getResult();
                     $thumbLayer->resizeInPixel($imageInfo['thumb_width'], $imageInfo['thumb_height'], true);
                     $thumbFrames[] = $thumbLayer->getResult();
                 }
                 // Then we re-generate the GIF
                 require_once IA_INCLUDES . 'phpimageworkshop' . IA_DS . 'Core' . IA_DS . 'GifCreator.php';
                 $gc = new GifCreator\GifCreator();
                 $gc->create($retouchedFrames, $gfe->getFrameDurations(), 0);
                 file_put_contents($path . self::_createFilename($aName, $ext), $gc->getGif());
                 $thumbCreator = new GifCreator\GifCreator();
                 $thumbCreator->create($thumbFrames, $gfe->getFrameDurations(), 0);
                 file_put_contents($path . self::_createFilename($aName, $ext, true), $thumbCreator->getGif());
                 return self::_createFilename($folder . $aName, $ext, true);
             }
         }
         // save full image
         $largestSide = $imageInfo['image_width'] > $imageInfo['image_height'] ? $imageInfo['image_width'] : $imageInfo['image_height'];
         if ($largestSide) {
             $image->resizeByLargestSideInPixel($largestSide, true);
         }
         $image = self::_applyWaterMark($image);
         $image->save($path, self::_createFilename($aName, $ext));
         // generate thumbnail
         $thumbWidth = $imageInfo['thumb_width'] ? $imageInfo['thumb_width'] : $this->iaCore->get('thumb_w');
         $thumbHeight = $imageInfo['thumb_height'] ? $imageInfo['thumb_height'] : $this->iaCore->get('thumb_h');
         if ($thumbWidth || $thumbHeight) {
             $thumb = ImageWorkshop::initFromPath($aFile['tmp_name']);
             switch ($imageInfo['resize_mode']) {
                 case self::FIT:
                     $thumb->resizeInPixel($thumbWidth, $thumbHeight, true, 0, 0, 'MM');
                     break;
                 case self::CROP:
                     $largestSide = $thumbWidth > $thumbHeight ? $thumbWidth : $thumbHeight;
                     $thumb->cropMaximumInPixel(0, 0, 'MM');
                     $thumb->resizeInPixel($largestSide, $largestSide);
                     $thumb->cropInPixel($thumbWidth, $thumbHeight, 0, 0, 'MM');
             }
             $thumb->save($path, self::_createFilename($aName, $ext, true));
         }
     } catch (Exception $e) {
         $this->iaView->setMessages(iaLanguage::get('invalid_image_file'));
         return false;
     }
     return self::_createFilename($folder . $aName, $ext, true);
 }
function find_dominant_colour($orig)
{
    $imgFolder = "img/ImageWorkshop";
    // werk it
    $werk = ImageWorkshop::initFromPath(__DIR__ . '/../' . $orig);
    $werk->getHeight();
    $werk->getWidth();
    $werk->resizeInPixel(100, null, true);
    // blur it up a bit
    for ($i = 0; $i < 25; $i++) {
        $werk->applyFilter(IMG_FILTER_GAUSSIAN_BLUR);
    }
    // pixelate the sh*t out of it
    $werk->applyFilter(IMG_FILTER_PIXELATE, 20);
    $werk->resizeInPixel(10, 10, false);
    // Save the result
    $dirPath = __DIR__ . "/../" . $imgFolder;
    $filename = "palette-" . date("Ymd-His") . ".png";
    $createFolders = true;
    $backgroundColor = null;
    // transparent, only for PNG (otherwise it will be white if set null)
    $imageQuality = 95;
    // useless for GIF, usefull for PNG and JPEG (0 to 100%)
    $werk->save($dirPath, $filename, $createFolders, $backgroundColor, $imageQuality);
    // some x-y points in the 10x10 image to grab a colour from
    $imgPosition = array(array(0, 0), array(2, 3), array(4, 5), array(8, 9));
    $palettes = array();
    // open the image
    $im = imagecreatefrompng($dirPath . "/" . $filename);
    // extract colour values from each point
    foreach ($imgPosition as $position) {
        $rgb = imagecolorat($im, $position[0], $position[1]);
        $r = $rgb >> 16 & 0xff;
        $g = $rgb >> 8 & 0xff;
        $b = $rgb & 0xff;
        // add values to array of potential palettes
        array_push($palettes, array($r, $g, $b));
    }
    $besti = -1;
    //index
    $bestv = 255 * 3;
    //value
    // choose closest colour to r+g+b=300
    foreach ($palettes as $i => $palette) {
        $sum = $palette[0] + $palette[1] + $palette[2];
        $v = abs(300 - $sum);
        if ($v < $bestv) {
            $bestv = $v;
            $besti = $i;
        }
    }
    //$rgb = $palettes[$besti];
    // if r+g+b > 600, use black text
    //$bestv>600 ? $white=0 : $white=1;
    class dominantColour
    {
        public $palette;
        public function getPalette()
        {
            return $this->palette;
        }
        public function displayPalette()
        {
            echo $this->palette;
        }
        public function setPalette($set)
        {
            $this->palette = $set;
        }
        private $rbg;
        public function getRGB()
        {
            return $this->rgb;
        }
        public function setRGB($set)
        {
            $this->rgb = $set;
        }
        private $textColour = 'white';
        public function getTextColour()
        {
            return $this->textColour;
        }
        public function setTextColour($set)
        {
            $this->textColour = $set;
        }
        public function displayTextColour()
        {
            echo $this->textColour;
        }
        // arbitrary exaggeration value between tints...
        private $tintExaggeration = 22;
        public function setTintExaggeration($set)
        {
            $this->tintExaggeration = $set;
        }
        public function getTintExaggeration()
        {
            return $this->tintExaggeration;
        }
        private function calculateExaggeration($rgb, $diff, $direction)
        {
            $new = array();
            foreach ($rgb as $colour) {
                array_push($new, $colour += $diff * $direction);
            }
            return $new;
        }
        private function displayColour($colour)
        {
            echo "rgb(" . $colour[0] . "," . $colour[1] . "," . $colour[2] . ")";
        }
        public function getLighter()
        {
            return $this->calculateExaggeration($this->rgb, $this->tintExaggeration, 1);
        }
        public function getDarker()
        {
            return $this->calculateExaggeration($this->rgb, $this->tintExaggeration, -1);
        }
        public function displayRGB()
        {
            $this->displayColour($this->rgb);
        }
        public function displayLighter()
        {
            $this->displayColour($this->getLighter());
        }
        public function displayDarker()
        {
            $this->displayColour($this->getDarker());
        }
    }
    $colourClass = new dominantColour();
    $colourClass->setRGB($palettes[$besti]);
    $colourClass->setTintExaggeration(22);
    $colourClass->setPalette($imgFolder . "/" . $filename);
    // if r+g+b > 600, use black text
    if ($colourClass->rgb[0] + $colourClass->rgb[1] + $colourClass->rgb[2] > 600) {
        // color is too light to have enough contrast to see white text
        $colourClass->setTextColour('black');
    }
    return $colourClass;
}
 public function cropPicture($crop = null, $path)
 {
     //如果不裁剪,则发生错误
     if (!$crop) {
         $this->error('必须裁剪');
     }
     $driver = modC('PICTURE_UPLOAD_DRIVER', 'local', 'config');
     if (strtolower($driver) == 'local') {
         //解析crop参数
         $crop = explode(',', $crop);
         $x = $crop[0];
         $y = $crop[1];
         $width = $crop[2];
         $height = $crop[3];
         //本地环境
         $image = ImageWorkshop::initFromPath($path);
         //生成将单位换算成为像素
         $x = $x * $image->getWidth();
         $y = $y * $image->getHeight();
         $width = $width * $image->getWidth();
         $height = $height * $image->getHeight();
         //如果宽度和高度近似相等,则令宽和高一样
         if (abs($height - $width) < $height * 0.01) {
             $height = min($height, $width);
             $width = $height;
         }
         //调用组件裁剪头像
         $image = ImageWorkshop::initFromPath($path);
         $image->crop(ImageWorkshopLayer::UNIT_PIXEL, $width, $height, $x, $y);
         $image->save(dirname($path), basename($path));
         //返回新文件的路径
         return cut_str('/Uploads/Avatar', $path, 'l');
     } else {
         $name = get_addon_class($driver);
         $class = new $name();
         $new_img = $class->crop($path, $crop);
         return $new_img;
     }
 }
    if ($file['error'] > 0) {
        die(json_encode(array('status' => 'error', 'message' => 'Ошибка, попробуйте ещё раз')));
    }
    // Проверяем тип файла
    if (!in_array($file['type'], $validTypes)) {
        die(json_encode(array('status' => 'error', 'message' => 'Запрещённый тип файла')));
    }
    // проверяем на скрипты
    foreach ($blackList as $item) {
        if (preg_match("/{$item}\$/i", $file['name'])) {
            die(json_encode(array('status' => 'error', 'message' => 'Запрещено загружать скрипты')));
        }
    }
    // Проверяем размер файла
    if ($file['size'] > $maxSize) {
        die(json_encode(array('status' => 'error', 'message' => 'Слишком большой размер файла')));
    }
    $newFileName = time() . '-' . strtolower($file['name']);
    if (move_uploaded_file($file['tmp_name'], $newFileName)) {
        echo 'WOW!';
        //echo json_encode(array('status' => 'success', 'url' => 'php/'.$path.$newFileName, 'width' => $width, 'height' => $height));
    } else {
        die(json_encode(array('status' => 'error', 'message' => 'Ошибка, попробуйте ещё раз')));
    }
    //$processImage = WideImage::load($file['tmp_name']);
    $processImage = ImageWorkshop::initFromPath($newFileName);
    //$resizedImage = $processImage->resize($minWidth, $minHeight, 'inside', 'down');
    //$resizedImage->saveToFile($path.$newFileName);
    //$width = $resizedImage->getWidth();
    //$height = $resizedImage->getHeight();
}
Exemple #29
0
 /**
  * Save image to file
  *
  * @param ImageWorkshop $image
  * @return Array
  */
 public function saveImage($image)
 {
     $dir = public_path('/assets/posts');
     $filetype = 'png';
     // Create a random string for Filename (and check not already used)
     do {
         $filename = uniqid();
     } while (file_exists($dir . DIRECTORY_SEPARATOR . $filename . '.' . $filetype));
     // ImageWorkshop Options
     $createFolders = false;
     $backgroundColor = null;
     $imageQuality = 95;
     // Attempt Save or Fail
     try {
         $image->save($dir, $filename . '.' . $filetype, $createFolders, $backgroundColor, $imageQuality);
     } catch (Exception $e) {
         return $e;
     }
     return array('filename' => $filename, 'filetype' => $filetype, 'image_url' => $dir . DIRECTORY_SEPARATOR . $filename . '.' . $filetype);
 }
Exemple #30
0
 /**
  * Preview style for images on backend.
  *
  * @static
  * @access     public
  * @param      string $sImageDir
  * @param      string $sImageName
  * @return     string
  * @since      1.0.0-alpha
  * @version    1.0.0-alpha
  */
 public static function styleColorbox($sImageDir, $sImageName)
 {
     $oLayer = ImageWorkshop::initFromPath($sImageDir . '/' . $sImageName);
     $oLayer->resizeToFit(400, 400, TRUE);
     return static::factory()->save($oLayer, $sImageDir, $sImageName);
 }