Resizes, commits image to storage, and returns field's value just before saving.
515640
def pre_save(self, model_instance, add):
        
        file = getattr(model_instance, self.attname)
        if file and not file._committed:
            file.name = self._clean_file_name(model_instance, file.name)
            file.file = self._resize_image(model_instance, file)
            file.save(file.name, file, save=False)
        return file
1653
public function beforeSave()
    {
        if ($this->file instanceof UploadedFile) {

            if (true !== $this->owner->isNewRecord) {
                /** @var ActiveRecord $oldModel */
                $oldModel = $this->owner->findOne($this->owner->primaryKey);
                $behavior = static::getInstance($oldModel, $this->attribute);
                $behavior->cleanFiles();
            }

            $this->owner->{$this->attribute} = implode('.',
                array_filter([$this->file->baseName, $this->file->extension])
            );
        } else {
            if (true !== $this->owner->isNewRecord && empty($this->owner->{$this->attribute})) {
                $this->owner->{$this->attribute} = ArrayHelper::getValue($this->owner->oldAttributes, $this->attribute,
                    null);
            }
        }
    }
757955
private void putResize (K key, V value) {
		// Check for empty buckets.
		int hashCode = System.identityHashCode(key);
		int index1 = hashCode & mask;
		K key1 = keyTable[index1];
		if (key1 == null) {
			keyTable[index1] = key;
			valueTable[index1] = value;
			if (size++ >= threshold) resize(capacity << 1);
			return;
		}

		int index2 = hash2(hashCode);
		K key2 = keyTable[index2];
		if (key2 == null) {
			keyTable[index2] = key;
			valueTable[index2] = value;
			if (size++ >= threshold) resize(capacity << 1);
			return;
		}

		int index3 = hash3(hashCode);
		K key3 = keyTable[index3];
		if (key3 == null) {
			keyTable[index3] = key;
			valueTable[index3] = value;
			if (size++ >= threshold) resize(capacity << 1);
			return;
		}

		int index4 = -1;
		K key4 = null;
		if (bigTable) {
			index4 = hash4(hashCode);
			key4 = keyTable[index4];
			if (key4 == null) {
				keyTable[index4] = key;
				valueTable[index4] = value;
				if (size++ >= threshold) resize(capacity << 1);
				return;
			}
		}

		push(key, value, index1, key1, index2, key2, index3, key3, index4, key4);
	}
1244955
def cropped_and_resized(size)
      normalized do |image|
        if record.cropped? || size != record.size
          image.crop(image_sizing.crop_geometry_string(size))
          image.resize(size)
        end
      end
    end
1123965
private void savePreviousImageValues() {
        if (matrix != null && viewHeight != 0 && viewWidth != 0) {
            matrix.getValues(m);
            prevMatrix.setValues(m);
            prevMatchViewHeight = matchViewHeight;
            prevMatchViewWidth = matchViewWidth;
            prevViewHeight = viewHeight;
            prevViewWidth = viewWidth;
        }
    }
997121
function(fileId, imgOrCanvas, maxSize, fromServer, customResizeFunction) {
            var promiseToReturn = new qq.Promise(),
                fileOrUrl, options;

            if (this._imageGenerator) {
                fileOrUrl = this._thumbnailUrls[fileId];
                options = {
                    customResizeFunction: customResizeFunction,
                    maxSize: maxSize > 0 ? maxSize : null,
                    scale: maxSize > 0
                };

                // If client-side preview generation is possible
                // and we are not specifically looking for the image URl returned by the server...
                if (!fromServer && qq.supportedFeatures.imagePreviews) {
                    fileOrUrl = this.getFile(fileId);
                }

                /* jshint eqeqeq:false,eqnull:true */
                if (fileOrUrl == null) {
                    promiseToReturn.failure({container: imgOrCanvas, error: "File or URL not found."});
                }
                else {
                    this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options).then(
                        function success(modifiedContainer) {
                            promiseToReturn.success(modifiedContainer);
                        },

                        function failure(container, reason) {
                            promiseToReturn.failure({container: container, error: reason || "Problem generating thumbnail"});
                        }
                    );
                }
            }
            else {
                promiseToReturn.failure({container: imgOrCanvas, error: "Missing image generator module"});
            }

            return promiseToReturn;
        }
1050346
def clean(self, value):
        
        if isinstance(value, FileStorage):
            return self.storage.save(value)
        return value
416258
def resize_image(image_str_tensor):
  """"""

  image = decode_and_resize(image_str_tensor)
  image = tf.image.encode_jpeg(image, quality=100)
  return image
1048109
public function getResizedImage(
        File $file,
        $urlType = 'default',
        $width = 100,
        $height = null,
        $crop = true,
        $filename = null,
        $quality = null
    ) {
        if ($crop) {
            return $this->getCroppedImage($file, $urlType, $width, $height, $filename, $quality);
        }

        if ($height == null) {
            $height = $width;
        }

        if ($this->repository) {
            if ($file->isImage()) {
                $filename = $this->determineFileName($file, $width, $height, 'r', $filename);

                if ($this->mustBuildImage($file, $filename)) {
                    $binary = $this->getBinary($file);

                    if ($this->keepOriginalImage($binary, $width, $height)) {
                        return $this->getOriginalImage($file, $urlType, $filename);
                    }

                    if ($binary) {
                        $imagine = new Imagine();
                        $image   = $imagine->load($binary);

                        $image->resize(new Box($width, $height));

                        $quality = $this->determineQuality($quality);
                        $image->save($this->basePath . '/' . $filename, array('quality' => $quality));
                    } else {
                        return false;
                    }
                }

                $url = $this->baseUrl . '/' . $filename;
                $file->addUrl($urlType, $url);

                return $file;
            }
        }

        return false;
    }
990699
def resize_image(self, data, size):
        
        from machina.core.compat import PILImage as Image
        image = Image.open(BytesIO(data))

        # Resize!
        image.thumbnail(size, Image.ANTIALIAS)

        string = BytesIO()
        image.save(string, format='PNG')
        return string.getvalue()
1206814
private function do_resize($image, $save_path, $image_quality)
    {
        $image = $this->open_image($image);

        $this->width  = imagesx($image);
        $this->height = imagesy($image);

        // Get optimal width and height - based on $option.
        $option_array = $this->get_dimensions($this->new_width, $this->new_height, $this->option);

        $optimal_width  = $option_array['optimal_width'];
        $optimal_height = $option_array['optimal_height'];

        // Resample - create image canvas of x, y size.
        $this->image_resized = imagecreatetruecolor($optimal_width, $optimal_height);

        // Retain transparency for PNG and GIF files.
        imagecolortransparent($this->image_resized, imagecolorallocatealpha($this->image_resized, 255, 255, 255, 127));
        imagealphablending($this->image_resized, false);
        imagesavealpha($this->image_resized, true);

        // Create the new image.
        imagecopyresampled($this->image_resized, $image, 0, 0, 0, 0, $optimal_width, $optimal_height, $this->width, $this->height);

        // if option is 'crop' or 'fit', then crop too
        if ($this->option == 'crop' || $this->option == 'fit') {
            $this->crop($optimal_width, $optimal_height, $this->new_width, $this->new_height);
        }

        // Get extension of the output file
        $extension = strtolower(File::extension($save_path));

        // Create and save an image based on it's extension
        switch ($extension) {
            case 'jpg':
            case 'jpeg':
                if (imagetypes() & IMG_JPG) {
                    imagejpeg($this->image_resized, $save_path, $image_quality);
                }
                break;

            case 'gif':
                if (imagetypes() & IMG_GIF) {
                    imagegif($this->image_resized, $save_path);
                }
                break;

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

                // Invert quality setting as 0 is best, not 9
                $invert_scale_quality = 9 - $scale_quality;

                if (imagetypes() & IMG_PNG) {
                    imagepng($this->image_resized, $save_path, $invert_scale_quality);
                }
                break;

            default:
                return false;
                break;
        }

        // Remove the resource for the resized image
        imagedestroy($this->image_resized);

        return true;
    }
1142849
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);
        }
    }
444780
def save(self, *args, **kwargs):
        
        if not self.pk and not self.slug:
            self.slug = self.generate_slug()

        if self.__original_file and self.file != self.__original_file:
            self.delete_real_file(self.__original_file)

        file_changed = True
        if self.pk:
            new_value = getattr(self, 'file')
            if hasattr(new_value, "file"):
                file_changed = isinstance(new_value.file, UploadedFile)
        else:
            self.cbversion = 0

        if file_changed:
            self.user_filename = os.path.basename(self.file.name)
            self.cbversion = self.cbversion + 1

        if not self.title:
            self.title = self.user_filename

        super(AssetBase, self).save(*args, **kwargs)

        if file_changed:
            signals.file_saved.send(self.file.name)
            utils.update_cache_bust_version(self.file.url, self.cbversion)
            self.reset_crops()

        if self.__original_file and self.file.name != self.__original_file.name:
            with manager.SwitchSchemaManager(None):
                for related in self.__class__._meta.get_all_related_objects(
                        include_hidden=True):
                    field = related.field
                    if getattr(field, 'denormalize', None):
                        cname = field.get_denormalized_field_name(field.name)
                        if getattr(field, 'denormalize'):
                            related.model.objects.filter(**{
                                field.name: self.pk
                            }).update(**{
                                cname: self.file.name
                            })
87183
def resize(image, width=None, height=None, crop=False, namespace="resized"):
    
    return resize_lazy(image=image, width=width, height=height, crop=crop,
                       namespace=namespace, as_url=True)
1095585
def clean_picture(self):
        
        if self.cleaned_data.get('picture'):
            picture_data = self.cleaned_data['picture']
            if 'error' in picture_data:
                raise forms.ValidationError(_(u'Upload a valid image. '
                            'The file you uploaded was either not an image '
                            'or a corrupted image.'))
                
            content_type = picture_data.content_type
            if content_type:
                main, sub = content_type.split('/')
                if not (main == 'image' 
                            and sub in defaults.ACCOUNTS_PICTURE_FORMATS):
                    raise forms.ValidationError(_(u'%s only.' % 
                                    defaults.ACCOUNTS_PICTURE_FORMATS))
        
            if picture_data.size > int(defaults.ACCOUNTS_PICTURE_MAX_FILE):
                raise forms.ValidationError(_(u'Image size is too big.'))
            return self.cleaned_data['picture']
683107
function original(callback) {
      if ((!trash) && (attachment.trash === undefined)) {
        // Trash status not set at all yet means
        // it'll be a live file as of this point,
        // skip extra API calls
        return callback(null);
      }
      var sizes;
      if (!_.contains([ 'gif', 'jpg', 'png' ], self.resolveExtension(attachment.extension))) {
        sizes = [ { name: 'original' } ];
      } else {
        sizes = self.imageSizes.concat([ { name: 'original' } ]);
      }
      return async.eachSeries(sizes, function(size, callback) {
        if (size.name === self.sizeAvailableInTrash) {
          // This size is always kept accessible for preview
          // in the media library
          return callback(null);
        }
        var path = self.url(attachment, { uploadfsPath: true, size: size.name });
        return method(path, function(err) {
          if (err) {
            // afterSave is not a good place for fatal errors
            self.apos.utils.warn('Unable to set permissions on ' + path + ', most likely already done');
          }
          return callback(null);
        });
      }, callback);
    }
549595
private boolean resizeAndSaveImage(int maxWidth, int maxHeight) throws IOException {
		// Decode image file, compress and re-save it
		boolean saved = false;
		File targetFile = configuration.diskCache.get(uri);
		if (targetFile != null && targetFile.exists()) {
			ImageSize targetImageSize = new ImageSize(maxWidth, maxHeight);
			DisplayImageOptions specialOptions = new DisplayImageOptions.Builder().cloneFrom(options)
					.imageScaleType(ImageScaleType.IN_SAMPLE_INT).build();
			ImageDecodingInfo decodingInfo = new ImageDecodingInfo(memoryCacheKey,
					Scheme.FILE.wrap(targetFile.getAbsolutePath()), uri, targetImageSize, ViewScaleType.FIT_INSIDE,
					getDownloader(), specialOptions);
			Bitmap bmp = decoder.decode(decodingInfo);
			if (bmp != null && configuration.processorForDiskCache != null) {
				L.d(LOG_PROCESS_IMAGE_BEFORE_CACHE_ON_DISK, memoryCacheKey);
				bmp = configuration.processorForDiskCache.process(bmp);
				if (bmp == null) {
					L.e(ERROR_PROCESSOR_FOR_DISK_CACHE_NULL, memoryCacheKey);
				}
			}
			if (bmp != null) {
				saved = configuration.diskCache.save(uri, bmp);
				bmp.recycle();
			}
		}
		return saved;
	}