Set image

@param string $keyImg Key from the image
@param file $imgFile The image

@throws \Exception

@return void|string
969207
protected function setImage($keyImg, $imgFile)
    {
        // If it's false or null we have to remove it from the server
        if (!$imgFile || is_null($imgFile)) {
            return $this->removeImage($keyImg);
        }
        if (strpos($imgFile['name'], '.php') !== false) {
            throw new \Exception('For security reasons, the extension ".php" cannot be in your file name.');
        }
        $avatar = wp_handle_upload($_FILES[$keyImg],
            [
                'mimes' => [
                    'jpg|jpeg|jpe' => 'image/jpeg',
                    'gif' => 'image/gif',
                    'png' => 'image/png',
                ],
                'test_form' => false,
                'unique_filename_callback' => function ($dir, $name, $ext) use ($keyImg) {
                    $name = $base_name = sanitize_file_name($this->user_login . '_' . $keyImg);
                    $number = 1;
                    while (file_exists($dir . "/$name$ext")) {
                        $name = $base_name . '_' . $number;
                        $number++;
                    }
                    return $name . $ext;
                },
            ]);
        // Remove the last image
        $this->removeImage($keyImg);

        $metaValue = [];

        $url_or_media_id = $avatar['url'];
        // Set the new image
        if (is_int($url_or_media_id)) {
            $metaValue['media_id'] = $url_or_media_id;
            $url_or_media_id = wp_get_attachment_url($url_or_media_id);
        }
        $metaValue['full'] = $url_or_media_id;
        return update_user_meta($this->ID, $keyImg, $metaValue);
    }
1053227
protected function getImage($keyImg, $sizeW, $sizeH = false)
    {
        $sizeH = ($sizeH) ? $sizeH : $sizeW;
        // fetch local avatar from meta and make sure it's properly ste
        $local_avatars = get_user_meta($this->ID, $keyImg, true);
        if (empty($local_avatars['full'])) {
            return '';
        }
        // generate a new size
        if (!array_key_exists($sizeW, $local_avatars)) {
            $local_avatars[$sizeW] = $local_avatars['full']; // just in case of failure elsewhere
            $upload_path = wp_upload_dir();
            // get path for image by converting URL, unless its already been set, thanks to using
            // media library approach
            if (!isset($avatar_full_path)) {
                $avatar_full_path = str_replace($upload_path['baseurl'], $upload_path['basedir'],
                    $local_avatars['full']);
            }
            // generate the new size
            $editor = wp_get_image_editor($avatar_full_path);
            if (!is_wp_error($editor)) {
                $resized = $editor->resize($sizeW, $sizeH, true);
                if (!is_wp_error($resized)) {
                    $dest_file = $editor->generate_filename();
                    $saved = $editor->save($dest_file);
                    if (!is_wp_error($saved)) {
                        $local_avatars[$sizeW] = str_replace($upload_path['basedir'], $upload_path['baseurl'],
                            $dest_file);
                    }
                }
            }
            // save updated avatar sizes
            update_user_meta($user_id, $keyImg, $local_avatars);
        }
        if ('http' != substr($local_avatars[$sizeW], 0, 4)) {
            $local_avatars[$sizeW] = home_url($local_avatars[$sizeW]);
        }
        return esc_url($local_avatars[$sizeW]);
    }
330882
public void setImage(BufferedImage img) {
        this.img = img;
        Dimension dim;
        if (img != null) {
            dim = new Dimension(img.getWidth(), img.getHeight());
        } else {
            dim = new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
        }

        setSize(dim);
        setPreferredSize(dim);
        repaint();
    }
976767
public function setImagineImage(ImagineImageInterface $imagineImage, $mimeType = null)
    {
        if (!$mimeType) {
            $mimeType = $this->getMimeType();
        }
        if ($this->imagineImage !== $imagineImage || $mimeType != $this->getMimeType()) {
            // imagine image was changed OR MIME type was changed
            //  -> we flag binary content to be regerated from imagine image
            if ($this->imagineImage !== $imagineImage) {
                $this->imagineImage = $imagineImage;
            }
            if ($this->mimeType !== $mimeType) {
                $this->mimeType = $mimeType;
            }
            $this->binaryContentDirty = true;
        }
    }
745345
def setImageItem(self, img):
        
        self.imageItem = weakref.ref(img)
        img.sigImageChanged.connect(self.imageChanged)
        img.setLookupTable(self.getLookupTable)  ## send function pointer, not the result
        #self.gradientChanged()
        self.regionChanged()
        self.imageChanged(autoLevel=True)
1102783
private static function remove_alpha_imagick(\Imagick $img){
    if ( $img->getImageAlphaChannel() ){
      $img->setImageBackgroundColor('#FFFFFF');
      $img->setImageAlphaChannel(11);
      //$img->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN);
      //$img->transformImageColorspace(\Imagick::COLORSPACE_RGB);
    }
    return $img;
  }
308925
public function setImageManager(ImageManager $imageManager = null, array $config = [])
    {
        if (!$imageManager) {
            $imageManager = new ImageManager($config);
        }
        $this->imageManager = $imageManager;

        return $this;
    }
1008978
public void setImage(BufferedImage im) {
		icon.setImage(im);
		if (image == null) {
			this.image = im;
//			this.setSize(image.getWidth(), image.getHeight());
			int panelX = image.getWidth(); 
			int panelY = image.getHeight(); 
			panel.setSize(panelX, panelY);

//			Toolkit tk = Toolkit.getDefaultToolkit();  
//			int xSize = ((int) tk.getScreenSize().getWidth());  
//			int ySize = ((int) tk.getScreenSize().getHeight());
			
			try {
				UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedLookAndFeelException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
			Rectangle bounds = ge.getMaximumWindowBounds();

			int deltaX = 30;
			int deltaY = 50;
			int xSize = Math.min(bounds.width, panelX+deltaX);
			int ySize = Math.min(bounds.height, panelY+deltaY);
			
			this.setPreferredSize(new Dimension(xSize, ySize));
			
			this.setResizable(true);
			this.pack();
		}
		this.getContentPane().repaint();
		if (!this.isVisible()) this.setVisible(true);
	}
1125153
public function setFile(PhingFile $src)
    {
        $fs = new FileSet();
        $fs->setFile($src);
        $this->addFileSet($fs);
    }
182330
def add_image(self, im):
        
        for im_tmp in self.images:
            if im_tmp.kind == im.kind:
                self.images.remove(im_tmp)
                break
        self.images.append(im)
115600
public function setImageSet($imageSet)
    {
        if (! in_array($imageSet, $this->availableImageSets)) {
            throw new \InvalidArgumentException('Invalid Gravatar image set.');
        }

        $this->imageSet = $imageSet;
    }
1037774
public function shortcutThumbnail(
        $srcImg,
        $stampImg = null,
        $targetDirPath = null,
        $filename = null // Just the filename, no extension
) {
        if (!$this->isGdLoaded) {
            throw new UnloadedExtensionException('The GD extension is missing \n');
        }

        $ds = DIRECTORY_SEPARATOR;
        if (is_null($stampImg) || !$this->fs->exists($stampImg)) {
            $stampImg = "{$this->webDir}{$ds}".$this->getDefaultStampRelativeUrl();
        }
        // Get image and its extension
        list($im, $extension) = $this->getImageAndExtensionFromUrl($srcImg);
        // Get stamp and its extension
        list($stamp, $stampExtension) = $this->getImageAndExtensionFromUrl($stampImg);

        if (is_null($filename)) {
            $filename = "{$this->ut->generateGuid()}.{$extension}";
        } else {
            $filename .= ".{$extension}";
        }

        if (!empty($targetDirPath)) {
            $dir = $targetDirPath.$ds.$filename;
        } else {
            $dir = $this->thumbnailDir.$ds.$filename;
        }

        if ('svg' === $extension) {
            if ('svg' === $stampExtension) {
                // Add all elements of $stamp to $im
                $stampDocument = $stamp->getDocument();
                $imDocument = $im->getDocument();
                $stampDocument->setHeight($imDocument->getHeight());
                $stampDocument->setWidth($imDocument->getWidth());
                $shortcut = new SVGImage($imDocument->getWidth(), $imDocument->getHeight());
                $shortcut->getDocument()->addChild($imDocument);
                $shortcut->getDocument()->addChild($stampDocument);
                $im = $shortcut;
            } else {
                $im->getDocument()->addChild(new SVGImageElement(
                    'data:'.mime_content_type($stampImg).';base64,'.base64_encode(file_get_contents($stampImg)),
                    0,
                    $im->getDocument()->getHeight() - imagesy($stamp),
                    imagesx($stamp),
                    imagesy($stamp)
                ));
            }
            $this->fs->dumpFile($dir, $im);
        } else {
            try {
                if ('svg' === $stampExtension) {
                    $stamp = $stamp->toRasterImage(imagesx($im), imagesy($im));
                }
                imagecopy($im, $stamp, 0, imagesy($im) - imagesy($stamp), 0, 0, imagesx($stamp), imagesy($stamp));
                $funcname = "image{$extension}";
                $funcname($im, $dir);
                imagedestroy($im);
                imagedestroy($stamp);
            } catch (\Exception $e) {
            }
        }

        return $dir;
    }
1364210
public function setImage(\Imagick $image)
    {
        $this->originalImage = $image;

        // set base image dimensions
        $this->setBaseDimensions(
            $this->originalImage->getImageWidth(),
            $this->originalImage->getImageHeight()
        );
        return $this;
    }
396286
public function setImageFormat($imageformat,$pngScaleFactor = null){
        if($imageformat == self::$IMAGE_FORMAT_JPEG){
            $this->imageDeviceCommand = "jpeg";
            $this->imageExtention="jpg";
            $this->pngDownScaleFactor = isset($pngScaleFactor) ? "-dDownScaleFactor=".$pngScaleFactor : "";
        }else if($imageformat == self::$IMAGE_FORMAT_PNG){
            $this->imageDeviceCommand = "png16m";
            $this->imageExtention="png";
            $this->pngDownScaleFactor = "";
        }
        return $this;
    }
972572
public function open($imgname){
        //检测图像文件
        if(!is_file($imgname)) E('不存在的图像文件');

        //销毁已存在的图像
        empty($this->img) || $this->img->destroy();

        //载入图像
        $this->img = new \Imagick(realpath($imgname));

        //设置图像信息
        $this->info = array(
            'width'  => $this->img->getImageWidth(),
            'height' => $this->img->getImageHeight(),
            'type'   => strtolower($this->img->getImageFormat()),
            'mime'   => $this->img->getImageMimeType(),
        );
    }
930799
public static function convertGDRessourceToImagick($imgRessource, $png = false)
  {
    ob_start();
    if ($png) {
      imagepng($imgRessource, null, 0);
    } else {
      imagejpeg($imgRessource, null, 100);
    }
    $blob = ob_get_clean();

    $image = new \Imagick();
    $image->readImageBlob($blob);

    return $image;
  }
96963
public function storeImage(ImageInterface $image, ImagePathInterface $path) {
		$this->optimizerImageManipulator->manipulateImage($image, $path);
		$this->writeImageFile($image, $path);
	}