toJpeg(string file[, function callback, int quality]])

Save palette as a new JPEG image.
@param file - new image file.
@param callback - call function after creating a palette.
@param quality - quality a new image, between 0 and 100 (inclusive).
182070
function(file, callback, quality) {
		quality = !quality?85:quality;
		
		var data = this.jpeg_encode.encode(this, quality);
		
		var fd =  this.fs.openSync(file, 'w');
		var bf = new Buffer(data);
		
		this.fs.writeSync(fd, bf, 0, bf.length);
		this.fs.closeSync(fd);
		
		if(callback) {
			callback.call(this);
		}
	}
416237
public static void save(Bitmap src, String fileName) throws ImageSaveException {
        saveJpeg(src, fileName, JPEG_QUALITY);
    }
177612
public function save($file = null, $quality = 95): void
	{
		$file = $file ?? $this->image;

		// Mage sure that the file or directory is writable

		if(file_exists($file))
		{
			if(!is_writable($file))
			{
				throw new RuntimeException(vsprintf('The file [ %s ] isn\'t writable.', [$file]));
			}
		}
		else
		{
			$pathInfo = pathinfo($file);

			if(!is_writable($pathInfo['dirname']))
			{
				throw new RuntimeException(vsprintf('The directory [ %s ] isn\'t writable.', [$pathInfo['dirname']]));
			}
		}

		// Save the image

		$this->processor->save($file, $this->normalizeImageQuality($quality));
	}
942101
public static void savePng(Bitmap src, String fileName) throws ImageSaveException {
        save(src, fileName, Bitmap.CompressFormat.PNG, 100);
    }
1045092
public function save($file, $type = 'guess', $quality = 80)
    {
        if ($file) {
            $directory = dirname($file);

            if (!is_dir($directory)) {
                @mkdir($directory, 0777, true);
            }
        }

        if (is_int($type)) {
            $quality = $type;
            $type = 'jpeg';
        }

        if ($type == 'guess') {
            $type = $this->guessType();
        }

        if (!isset(self::$types[$type])) {
            throw new \InvalidArgumentException('Given type ('.$type.') is not valid');
        }

        $type = self::$types[$type];

        try {
            $this->init();
            $this->applyOperations();

            $success = false;

            if (null == $file) {
                ob_start();
            }

            if ($type == 'jpeg') {
                $success = $this->getAdapter()->saveJpeg($file, $quality);
            }

            if ($type == 'gif') {
                $success = $this->getAdapter()->saveGif($file);
            }

            if ($type == 'png') {
                $success = $this->getAdapter()->savePng($file);
            }

            if ($type == 'webp') {
                $success = $this->getAdapter()->saveWebP($file, $quality);
            }

            if (!$success) {
                return false;
            }

            return null === $file ? ob_get_clean() : $file;
        } catch (\Exception $e) {
            if ($this->useFallbackImage) {
                return null === $file ? file_get_contents($this->fallback) : $this->getCacheFallback();
            } else {
                throw $e;
            }
        }
    }
1282581
function(file, content, callback) {
			fs.writeFile(file, content, 'ascii', function(err) {
				callback(err ? err : null);
			});
		}
1254445
public static void imgCompressByWH(String srcFile, String desFile, int width, int height, Float quality) {
        ImgCompressUtils.imgCompressByWH(srcFile, desFile, width, height, quality, false);
    }
849089
@Override
  public void transcodeWebpToJpeg(
      InputStream inputStream,
      OutputStream outputStream,
      int quality) throws IOException {
    StaticWebpNativeLoader.ensure();
    nativeTranscodeWebpToJpeg(
        Preconditions.checkNotNull(inputStream),
        Preconditions.checkNotNull(outputStream),
        quality);
  }
597684
@PreAuthorize("isAuthenticated()")
    public E saveImage(MultipartFile file, boolean createThumbnail, Integer thumbnailTargetSize)
        throws Exception {

        InputStream is = null;
        ByteArrayInputStream bais = null;
        E imageToPersist = null;

        try {
            is = file.getInputStream();
            byte[] imageByteArray = IOUtils.toByteArray(is);

            // create a new instance (generic)
            imageToPersist = getEntityClass().newInstance();

            // create a thumbnail if requested
            if (createThumbnail) {
                byte[] thumbnail = scaleImage(
                    imageByteArray,
                    FilenameUtils.getExtension(file.getOriginalFilename()),
                    thumbnailTargetSize);
                imageToPersist.setThumbnail(thumbnail);
            }

            // set binary image data
            imageToPersist.setFile(imageByteArray);

            // detect dimensions
            bais = new ByteArrayInputStream(imageByteArray);

            BufferedImage bimg = ImageIO.read(bais);

            // set basic image properties
            imageToPersist.setWidth(bimg.getWidth());
            imageToPersist.setHeight(bimg.getHeight());
            imageToPersist.setFileType(file.getContentType());
            imageToPersist.setFileName(file.getOriginalFilename());

            // persist the image
            dao.saveOrUpdate(imageToPersist);

        } catch (Exception e) {
            throw new Exception("Could not create the Image in DB: "
                + e.getMessage());
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(bais);
        }

        return imageToPersist;
    }
232268
function(callback) {
      var firstThumbnail;

      for (var i = 0; i < thumbnailsPaths.length; i++) {
        var thumbnailsPath = thumbnailsPaths[i].thumbnailPath;

        if (!firstThumbnail)
          firstThumbnail = gm(thumbnailsPath);
        else
          firstThumbnail.append(thumbnailsPath, horizontally);

        images.push({
          sprite: destinationPath,
          image: thumbnailsPaths[i].originalPath,
          x: horizontally ? width * i : 0,
          y: horizontally ? 0 : height * i
        });
      }
      firstThumbnail
        .quality(quality)
        .write(destinationPath, callback);
    }
30539
public static function saveImage( $fileName, $resource, $type = IMAGETYPE_PNG, $quality = 100 )
	{
		switch( $type )
		{
			case IMAGETYPE_PNG:
				ImagePNG( $resource, $fileName );
				break;
			case IMAGETYPE_JPEG:
				ImageJPEG( $resource, $fileName, $quality );
				break;
			case IMAGETYPE_GIF:
				ImageGIF( $resource, $fileName );
				break;
			default:
				throw new InvalidArgumentException( 'Invalid Image Type' );
		}
	}
1237996
function fileToCanvas(file, done) {
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');
  var img = document.createElement('img');
  img.onload = function() {
    canvas.width = img.naturalWidth;
    canvas.height = img.naturalHeight;
    ctx.drawImage(img, 0, 0);
    done(null, canvas);
  };
  img.onerror = function(err) {
    done(err);
  };
  img.src = URL.createObjectURL(file);
}
269723
public void addPatternFromFile(String file) throws IOException {

		File f = new File(file);
		addPatternFromReader(new FileReader(f));
	}
1354318
function _filesToString (files, encoding, separator, callback) {

			if ("undefined" === typeof files) {
				throw new ReferenceError("missing \"files\" argument");
			}
				else if ("object" !== typeof files || !(files instanceof Array)) {
					throw new TypeError("\"files\" argument is not an Array");
				}
			else if ("undefined" === typeof callback && "undefined" === typeof separator && "undefined" === typeof encoding) {
				throw new ReferenceError("missing \"callback\" argument");
			}
				else if ("function" !== typeof callback && "function" !== typeof separator && "function" !== typeof encoding) {
					throw new TypeError("\"callback\" argument is not a function");
				}
			else {

				let _callback = callback;

				if ("undefined" === typeof _callback) {

					if ("undefined" === typeof separator) {
						_callback = encoding;
					}
					else {
						_callback = separator;
					}

				}

				filesToStreamProm(files, "string" === typeof separator ? separator : " ").then((readStream) => {

					return new Promise((resolve, reject) => {

						let data = "";
						let error = false;

						readStream.once("error", (_err) => {

							error = true;
							reject(_err);

						}).on("data", (chunk) => {
							data += chunk.toString("string" === typeof encoding ? encoding : "utf8");
						}).once("end", () => {

							if (!error) {
								resolve(data);
							}

						});

					});

				}).then((data) => {
					_callback(null, data);
				}).catch(_callback);

			}

		}
1200338
function(callback) {
		
		if(!this.ifLoad) {
			this.history.push('add to stack task: jpegToData');
			this.stack(this.jpegToData, callback);
			return;
		} 
		
		var that = this;
		
		this.history.push('jpeg decode');
		var jpeg = new this.jpeg_node();

		jpeg.parse(new Uint8Array(this.data));
		jpeg.decode(function(pixels) {
			that.width = jpeg.width;
			that.height = jpeg.height;
			that.bpp = 4;
			that.data = pixels;
			callback.call(that);
		});
	}
82309
def _write_openjpeg(self, img_array, verbose=False):
        
        if img_array.ndim == 2:
            # Force the image to be 3D.  Just makes things easier later on.
            img_array = img_array.reshape(img_array.shape[0],
                                          img_array.shape[1],
                                          1)

        self._populate_comptparms(img_array)

        with ExitStack() as stack:
            image = opj.image_create(self._comptparms, self._colorspace)
            stack.callback(opj.image_destroy, image)

            numrows, numcols, numlayers = img_array.shape

            # set image offset and reference grid
            image.contents.x0 = self._cparams.image_offset_x0
            image.contents.y0 = self._cparams.image_offset_y0
            image.contents.x1 = (image.contents.x0 +
                                 (numcols - 1) * self._cparams.subsampling_dx +
                                 1)
            image.contents.y1 = (image.contents.y0 +
                                 (numrows - 1) * self._cparams.subsampling_dy +
                                 1)

            # Stage the image data to the openjpeg data structure.
            for k in range(0, numlayers):
                layer = np.ascontiguousarray(img_array[:, :, k],
                                             dtype=np.int32)
                dest = image.contents.comps[k].data
                src = layer.ctypes.data
                ctypes.memmove(dest, src, layer.nbytes)

            cinfo = opj.create_compress(self._cparams.codec_fmt)
            stack.callback(opj.destroy_compress, cinfo)

            # Setup the info, warning, and error handlers.
            # Always use the warning and error handler.  Use of an info
            # handler is optional.
            event_mgr = opj.EventMgrType()
            _info_handler = _INFO_CALLBACK if verbose else None
            event_mgr.info_handler = _info_handler
            event_mgr.warning_handler = ctypes.cast(_WARNING_CALLBACK,
                                                    ctypes.c_void_p)
            event_mgr.error_handler = ctypes.cast(_ERROR_CALLBACK,
                                                  ctypes.c_void_p)

            opj.setup_encoder(cinfo, ctypes.byref(self._cparams), image)

            cio = opj.cio_open(cinfo)
            stack.callback(opj.cio_close, cio)

            if not opj.encode(cinfo, cio, image):
                raise IOError("Encode error.")

            pos = opj.cio_tell(cio)

            blob = ctypes.string_at(cio.contents.buffer, pos)
            fptr = open(self.filename, 'wb')
            stack.callback(fptr.close)
            fptr.write(blob)

        self.parse()
1149134
function(callback) {
      var asyncFunctions = [];

      for (var i = 0; i < numberOfRows; i++) {
        var rowsImagesPaths = imagesPaths.slice(i * numberOfColumns, i * numberOfColumns + numberOfColumns);
        var lineWidth = width;
        var lineHeight = height;
        var linePath = path.join(temporaryDirectoryPath, 'line-' + i);

        linesPaths.push(linePath);
        asyncFunctions.push(createLine(rowsImagesPaths, linePath, lineWidth, lineHeight, true, 100));
      }

      async.parallel(asyncFunctions, function(error, results) {
        if (error) return callback(error);

        results.forEach(function(line) {
          line.forEach(function(image) {
            if (image.image === path.join(temporaryDirectoryPath, 'transparent.png')) return;

            var spritePathChunks = path.parse(image.sprite).name.match(/-([0-9]+)$/);
            var lineIndex = (spritePathChunks && parseInt(spritePathChunks[1])) || 0;

            image.y = image.y + (lineIndex * height);
            image.sprite = destinationPath;
            images.push(image);
          });
        });

        callback();
      });
    }