Saves a BMP image

This function has been published on the PHP website, and can be used freely

@access public
5911
function imagebmp(&$im, $filename = "") {

        if (!$im) return false;
        $w = imagesx($im);
        $h = imagesy($im);
        $result = '';

        // if the image is not true color, we convert it first
        if (!imageistruecolor($im)) {
            $tmp = imagecreatetruecolor($w, $h);
            imagecopy($tmp, $im, 0, 0, 0, 0, $w, $h);
            imagedestroy($im);
            $im = & $tmp;
        }

        $biBPLine = $w * 3;
        $biStride = ($biBPLine + 3) & ~3;
        $biSizeImage = $biStride * $h;
        $bfOffBits = 54;
        $bfSize = $bfOffBits + $biSizeImage;

        $result .= substr('BM', 0, 2);
        $result .=  pack ('VvvV', $bfSize, 0, 0, $bfOffBits);
        $result .= pack ('VVVvvVVVVVV', 40, $w, $h, 1, 24, 0, $biSizeImage, 0, 0, 0, 0);

        $numpad = $biStride - $biBPLine;
        for ($y = $h - 1; $y >= 0; --$y) {
            for ($x = 0; $x < $w; ++$x) {
                $col = imagecolorat ($im, $x, $y);
                $result .=  substr(pack ('V', $col), 0, 3);
            }
            for ($i = 0; $i < $numpad; ++$i)
                $result .= pack ('C', 0);
        }

        if($filename==""){
            echo $result;
        } else {
            $file = fopen($filename, "wb");
            fwrite($file, $result);
            fclose($file);
        }
        return true;
    }
1078249
function pixelate($size) {
		imagefilter($this->data,IMG_FILTER_PIXELATE,$size,TRUE);
		return $this->save();
	}
671544
def save_image(image, destination=None, filename=None, **options):
    
    if destination is None:
        destination = BytesIO()
    filename = filename or ''
    # Ensure plugins are fully loaded so that Image.EXTENSION is populated.
    Image.init()
    format = Image.EXTENSION.get(os.path.splitext(filename)[1].lower(), 'JPEG')
    if format in ('JPEG', 'WEBP'):
        options.setdefault('quality', 85)
    saved = False
    if format == 'JPEG':
        if image.mode.endswith('A'):
            # From PIL 4.2, saving an image with a transparency layer raises an
            # IOError, so explicitly remove it.
            image = image.convert(image.mode[:-1])
        if settings.THUMBNAIL_PROGRESSIVE and (
                max(image.size) >= settings.THUMBNAIL_PROGRESSIVE):
            options['progressive'] = True
        try:
            image.save(destination, format=format, optimize=1, **options)
            saved = True
        except IOError:
            # Try again, without optimization (PIL can't optimize an image
            # larger than ImageFile.MAXBLOCK, which is 64k by default). This
            # shouldn't be triggered very often these days, as recent versions
            # of pillow avoid the MAXBLOCK limitation.
            pass
    if not saved:
        image.save(destination, format=format, **options)
    if hasattr(destination, 'seek'):
        destination.seek(0)
    return destination
703111
def save_image(self, file_obj):
        
        manager = pyglet.image.get_buffer_manager()
        colorbuffer = manager.get_color_buffer()

        # if passed a string save by name
        if hasattr(file_obj, 'write'):
            colorbuffer.save(file=file_obj)
        else:
            colorbuffer.save(filename=file_obj)
810693
function cloneImage( $imageObject, $width, $height, $useTruecolor = null )
    {
        if ( $this->ImageObject !== null and
             $this->ImageObjectRef !== null )
        {
            $this->destroy();
        }
        $this->ImageObject = eZImageInterface::createImage( $width, $height, $useTruecolor );
        $this->IsTrueColor = $useTruecolor;
        $this->ImageObjectRef = eZImageInterface::registerImage( $this->ImageObject );
        ImageCopy( $this->ImageObject, $imageObject, 0, 0, 0, 0, $width, $height );
    }
1320911
public function save($string, $size, $color, $bg, $target)
    {
        return (!file_exists($target)) ? file_put_contents("$target", $this->getImgData($string, $size, $color, $bg)) : false;
    }
362972
def save_image(filename,view='axial',type='png',hostname=None):
    ''''''
    driver_send("SAVE_%s %simage %s" % (type.upper(),view.lower(),filename),hostname=hostname)
227268
def save(self, fn:PathOrStr):
        ""
        x = image2np(self.data*255).astype(np.uint8)
        PIL.Image.fromarray(x).save(fn)
63011
public function saveImage($savePath, $imageQuality = "100")
		# Author:     Jarrod Oberto
		# Date:       27-02-08
		# Purpose:    Saves the image
		# Param in:   $savePath: Where to save the image including filename:
		#             $imageQuality: image quality you want the image saved at 0-100
		# Param out:  n/a
		# Reference:
		# Notes:    * gif doesn't have a quality parameter
		#       * jpg has a quality setting 0-100 (100 being the best)
		#       * png has a quality setting 0-9 (0 being the best)
		#
		#             * bmp files have no native support for bmp files. We use a
		#       third party class to save as bmp.
	{

		// *** Perform a check or two.
		if ( ! is_resource($this->imageResized))
		{
			if ($this->debug)
			{
				throw new Exception('saveImage: This is not a resource.');
			}
			else
			{
				throw new Exception();
			}
		}
		$fileInfoArray = pathInfo($savePath);
		clearstatcache();
		if ( ! is_writable($fileInfoArray['dirname']))
		{
			if ($this->debug)
			{
				throw new Exception('The path is not writable. Please check your permissions.');
			}
			else
			{
				throw new Exception();
			}
		}

		// *** Get extension
		$extension = strrchr($savePath, '.');
		$extension = fix_strtolower($extension);

		$error = '';

		switch ($extension)
		{
			case '.jpg':
			case '.jpeg':
				$this->checkInterlaceImage($this->isInterlace);
				if (imagetypes() & IMG_JPG)
				{
					imagejpeg($this->imageResized, $savePath, $imageQuality);
				}
				else
				{
					$error = 'jpg';
				}
				break;

			case '.gif':
				$this->checkInterlaceImage($this->isInterlace);
				if (imagetypes() & IMG_GIF)
				{
					imagegif($this->imageResized, $savePath);
				}
				else
				{
					$error = 'gif';
				}
				break;

			case '.png':
				// *** Scale quality from 0-100 to 0-9
				$scaleQuality = round(($imageQuality / 100) * 9);

				// *** Invert qualit setting as 0 is best, not 9
				$invertScaleQuality = 9 - $scaleQuality;

				$this->checkInterlaceImage($this->isInterlace);
				if (imagetypes() & IMG_PNG)
				{
					imagepng($this->imageResized, $savePath, $invertScaleQuality);
				}
				else
				{
					$error = 'png';
				}
				break;

			case '.bmp':
				file_put_contents($savePath, $this->GD2BMPstring($this->imageResized));
				break;


			// ... etc

			default:
				// *** No extension - No save.
				$this->errorArray[] = 'This file type (' . $extension . ') is not supported. File not saved.';
				break;
		}

		//imagedestroy($this->imageResized);

		// *** Display error if a file type is not supported.
		if ($error != '')
		{
			$this->errorArray[] = $error . ' support is NOT enabled. File not saved.';
		}
	}
544390
public function image() {
        $tree = Globals::getTree();
        $cid   = Filter::get('cid');
        $certificate = null;
        if(!empty($cid)) $certificate =  Certificate::getInstance($cid, $tree, null, $this->provider);
        
        $imageBuilder = new ImageBuilder($certificate);
        
        if (!empty(Filter::get('cb'))) {
            $imageBuilder->setExpireOffset($imageBuilder->getExpireOffset() * 7);
        }
        
        $imageBuilder
            ->setShowWatermark(Auth::accessLevel($tree) >= $this->module->getSetting('MAJ_SHOW_NO_WATERMARK', Auth::PRIV_HIDE))
            ->setFontMaxSize($this->module->getSetting('MAJ_WM_FONT_MAXSIZE', 18))
            ->setFontColor($this->module->getSetting('MAJ_WM_FONT_COLOR', '#4D6DF3'))
        ;
        
        $imageBuilder->render();
        
    }
252056
def save_image(self, img, filename=None, **kwargs):  # floating_point=False,
        
        filename = filename or self.get_filename(**img.data.attrs)
        nt.save(img, filename, **kwargs)
479769
static function createImage( $width, $height, &$useTruecolor )
    {
        if ( $useTruecolor === null )
        {
//             print( "has GD2='" . eZImageInterface::hasGD2() . "'<br/>" );
            $useTruecolor = eZImageInterface::hasGD2();
        }
        if ( $useTruecolor and
             !function_exists( 'ImageCreateTrueColor' ) )
        {
            eZDebug::writeWarning( 'Function ImageCreateTrueColor does not exist, cannot create true color images', __METHOD__ );
            $useTruecolor = false;
        }
        if ( $useTruecolor )
            $imageObject = ImageCreateTrueColor( $width, $height );
        else
            $imageObject = ImageCreate( $width, $height );
        return $imageObject;
    }
990428
def save(output_filename, labels, palette, dpi, options):

    '''

    '''

    if not options.quiet:
        print('  saving {}...'.format(output_filename))

    if options.saturate:
        palette = palette.astype(np.float32)
        pmin = palette.min()
        pmax = palette.max()
        palette = 255 * (palette - pmin)/(pmax-pmin)
        palette = palette.astype(np.uint8)

    if options.white_bg:
        palette = palette.copy()
        palette[0] = (255, 255, 255)

    output_img = Image.fromarray(labels, 'P')
    output_img.putpalette(palette.flatten())
    output_img.save(output_filename, dpi=dpi)
998826
function save() {
		$fw=Base::instance();
		if ($this->flag) {
			if (!is_dir($dir=$fw->get('TEMP')))
				mkdir($dir,Base::MODE,TRUE);
			$this->count++;
			$fw->write($dir.'/'.
				$fw->hash($fw->get('ROOT').$fw->get('BASE')).'.'.
				$fw->hash($this->file).'-'.$this->count.'.png',
				$this->dump());
		}
		return $this;
	}
1160157
def save_png_bytes_io(self):
        
        bytearr = QtCore.QByteArray()
        buf = QtCore.QBuffer(bytearr)
        buf.open(QtCore.QIODevice.WriteOnly)
        self.contents.save(buf, "PNG")
        bio = io.BytesIO(bytearr.data())
        # DPI correction
        img = Image.open(bio)
        img = img.resize((self.screen_size[0], self.screen_size[1]),
                         Image.ANTIALIAS)
        img.info["dpi"] = (96, 96)
        converted = io.BytesIO()
        img.save(converted, format='png')
        return converted
917497
function setBackground()
  {
    $dat = @getimagesize($this->bgimg);
    if($dat == false) { return; }

    switch($dat[2]) {
      case 1:  $newim = @imagecreatefromgif($this->bgimg); break;
      case 2:  $newim = @imagecreatefromjpeg($this->bgimg); break;
      case 3:  $newim = @imagecreatefrompng($this->bgimg); break;
      case 15: $newim = @imagecreatefromwbmp($this->bgimg); break;
      case 16: $newim = @imagecreatefromxbm($this->bgimg); break;
      default: return;
    }

    if(!$newim) return;

    imagecopy($this->im, $newim, 0, 0, 0, 0, $this->image_width, $this->image_height);
  }
289593
private function upload_image()
    {

        /* validate the image */
        $validation    = Validator::make($this->image, array($this->input => $this->rules));
        $errors        = array();
        $original_name = $this->image[$this->input]->getClientOriginalName();
        $path          = '';
        $filename      = '';
        $resizes       = '';

        if ($validation->fails()) {
            /* use the messages object for the erros */
            $errors = implode('. ', $validation->messages()->all());
        } else {
            if ($this->random) {
                if (is_callable($this->random_cb)) {
                    $filename = call_user_func($this->random_cb, $original_name);
                } else {
                    $ext      = File::extension($original_name);
                    $filename = $this->generate_random_filename().'.'.$ext;
                }
            } else {
                $filename = $original_name;
            }

            /* upload the file */
            $save = $this->image[$this->input]->move($this->path, $filename);
            //$save = Input::upload($this->input, $this->path, $filename);

            if ($save) {
                $path = $this->path.$filename;

                if (is_array($this->image_sizes)) {
                    $resizer = new Resize();
                    $resizes = $resizer->create($save, $this->path, $filename, $this->image_sizes);
                }
            } else {
                $errors = 'Could not save image';
            }
        }

        return compact('errors', 'path', 'filename', 'original_name', 'resizes');
    }