Manipulating WebP Images

Convert GIFF Image Frame to WebP Image

Aspose.Imaging enables you to extract a frame or frames from any existing GIFF image and convert it to WebP format. This article shows how you can extract a particular frame from a GIFF image and convert it to a WebP image. Following are the steps to convert a GIFF frame to a WebP image.

  1. Load an existing GIFF image into an instance of Image using the factory method Load.
  2. Create and initialize an instance of GifImage class.
  3. Create and initialize an instance of WebPImage class.
  4. Access the GIFF image Frame with GifImage property.
  5. Create and initialize an instance of WebPFrameBlock class.
  6. Add WebP frame to WebP image block list.
  7. Set WebP image options.
  8. Save WebP image.

Following is the code demonstration.

// The path to the documents directory.
String dataDir = "D:/WebPImages/";
// Load GIFF image into the instance of image class.
try (GifImage gif = (GifImage)Image.load(dataDir + "asposelogo.gif"))
{
// Load an existing WebP image into the instance of WebPImage class.
try (WebPImage webp = new WebPImage(gif.getWidth(), gif.getHeight(), null))
{
// Loop through the GIFF frames
for (IGifBlock block : gif.getBlocks())
{
// Convert GIFF block to GIFF Frame
if (!(block instanceof GifFrameBlock))
{
continue;
}
GifFrameBlock gifBlock = (GifFrameBlock) block;
// Create an instance of WebP Frame instance by passing GIFF frame to class constructor.
WebPFrameBlock webBlock = new WebPFrameBlock(gifBlock);
webBlock.setTop((short)gifBlock.getTop());
webBlock.setLeft((short)gifBlock.getLeft());
webBlock.setDuration((short)gifBlock.getControlBlock().getDelayTime());
// Add WebP frame to WebP image block list
webp.addBlock(webBlock);
}
// Set Properties of WebP image.
webp.getOptions().setAnimBackgroundColor(0xff); // Black
webp.getOptions().setAnimLoopCount(0); // Infinity
webp.getOptions().setQuality(50);
webp.getOptions().setLossless(false);
// Save WebP image.
webp.save(dataDir + "ConvertGIFFImageFrame_out.webp");
}
}

Create WebP Image

WebP is a new image format that provides lossless and lossy compression for images on the web. Developers can use the WebP image format to create smaller and richer images that can help make the web faster. Using Aspose.Imaging for Java API developers can create WebP image. This article demonstrates the use of WebPOptions and Image classes to create a WebP image. The release of Aspose.Imaging for Java 3.3.0 contains the WebPOptions class. With the help of WebPOptions class developer can create WebP image. The code snippet provided below demonstrates how to use it.

// The path to the documents directory.
String dataDir = "D:/WebPImages/";
// Create an instance of WebPOptions class and set properties
try (WebPOptions imageOptions = new WebPOptions())
{
imageOptions.setLossless(true);
imageOptions.setSource(new FileCreateSource(dataDir + "CreatingWebPImage_out.webp", false));
// Create an instance of image class by using WebOptions instance that you have just created.
try (Image image = Image.create(imageOptions, 500, 500))
{
image.save();
}
}

Exporting Image to WebP

Aspose.Imaging lets you save files in Webp format. This article shows how to save a file in Webp format with Aspose.Imaging, and it also discusses some of the settings that can be used when saving to this format. WebPOptions is a specialized class in the ImageOptions namespace used to manipulate WebP images. To export to Webp, create an instance of the Image class, either loaded from an existing image file or created from scratch. This article explains how. In the example below, an existing image is loaded by passing the file path to the Image class static Load method. Once it is loaded, save the image using the Image class Save method, and supply a WebPOptions object as the second argument WebPOptions class properties can be set while conversion. Some of the properties are Quality and Lossless. Following is the code demonstration.

// The path to the documents directory.
String dataDir = "D:/WebPImages/";
// Create an instance of image class.
try (Image image = Image.load(dataDir + "SampleImage1.bmp"))
{
// Create an instance of WebPOptions class and set properties
try (WebPOptions options = new WebPOptions())
{
options.setQuality(50);
options.setLossless(false);
image.save(dataDir+ "ExportToWebP_out.webp", options);
}
}

Exporting WebP to Other Image Formats

Using Aspose.Imaging you can convert WebP image to other image formats. This article shows how you can convert a WebP image to other image format. In the example below, an existing WebP image is loaded by passing the file path to the Image class static Load method. Once it is loaded, save the image using the Image class Save method, and supply a instance of BmpOptions as the second argument. In this way a WebP image will be converted to a BMP image.

// The path to the documents directory.
String dataDir = "D:/WebPImages/";
// Load WebP image into the instance of image class.
try (Image image = Image.load(dataDir + "asposelogo.webp"))
{
// Save the image in WebP format.
image.save(dataDir + "ExportWebPToOtherImageFormats_out.bmp", new BmpOptions());
}

Extract Frames From WebP Image

Aspose.Imaging enables you to extract a frame or frames from any existing WebP image and convert it to other image formats. This article shows how you can extract a particular frame from a WebP image and convert it to a Raster image. Aspose.Imaging.FileFormats.Webp.WebPImage has a property called Blocks. Once an existing WebP image is loaded, Blocks property will contain the array of frames inside the WebP image. Using Blocks property you can access an individual frame image. In the example below, an existing WebP image is loaded by passing the file path to the Aspose.Imaging.FileFormats.Webp.WebPImage class. Once it is loaded, check the Blocks property. If it is greater then zero then it means frames inside the WebP image have been loaded. Now access a particular frame and convert it into any Raster Image.

// The path to the documents directory.
String dataDir = "D:/WebPImages/";
// Load an existing WebP image into the instance of WebPImage class.
try (WebPImage image = (WebPImage)Image.load(dataDir + "asposelogo.webp"))
{
if (image.getPageCount() > 2)
{
// Access a particular frame from WebP image and cast it to Raster Image
RasterImage block = (RasterImage)image.getPages()[2];
// Save the Raster Image to a BMP image.
block.save(dataDir + "ExtractFrameFromWebPImage.bmp", new BmpOptions());
}
}

Update WebP Image

There was an OutOfMemoryError when saving WebP file after resize, crop and rotate&flip actions. Aspose.Imaging for Java provides a simple solution to self-update WebP image. The following code snippet shows how to update the WebP file.

// The path to the documents directory.
String dataDir = "D:/WebPImages/";
String inputFile = dataDir + "Animation1.webp";
String outputFile = dataDir + "Animation2.webp";
try (ByteArrayOutputStream ms = new ByteArrayOutputStream())
{
try (WebPImage image = (WebPImage)Image.load(inputFile))
{
image.resize(300, 450, ResizeType.HighQualityResample);
image.crop(new Rectangle(10, 10, 200, 300));
image.rotateFlipAll(RotateFlipType.Rotate90FlipX);
image.save(ms);
}
try (FileOutputStream fs = new FileOutputStream(outputFile))
{
byte[] bytes = ms.toByteArray();
fs.write(bytes, 0, bytes.length);
}
}

Memory Strategy Optimization

Load and create of WebP images can be proceeded using memory strategy optimization - ie limiting memory buffer size for operation.

// Example 1. Setting a memory limit of 50 megabytes for operations on the created WebP image
try (WebPOptions imageOptions = new WebPOptions())
{
imageOptions.setSource(new FileCreateSource("created.webp", false));
imageOptions.setBufferSizeHint(50);
try (Image image = Image.create(imageOptions, 1000, 1000))
{
// Do something with the created image
image.save();
}
}
// Example 2. Setting a memory limit of 20 megabytes for operations on the loaded WebP image
LoadOptions loadOptions = new LoadOptions();
loadOptions.setBufferSizeHint(20);
try (Image image = Image.load("Lossless.webp", loadOptions))
{
// Do something with the loaded image
}
// Example 3. Settings a memory limit of 30 mebagytes for export-to-webp operation
LoadOptions loadOptions = new LoadOptions();
loadOptions.setBufferSizeHint(30);
try (Image image = Image.load("image.png", loadOptions))
{
image.save("exported.webp", new WebPOptions());
}

Batch export to WebP

Batch (sequential) export mode at all

Batch (or sequential) export mode eliminates the need to store the data of all pages of a multi-page image in memory.

This approach implements the idea of “Loading a page into memory from an input stream –> processing a page (for example, a rotation operation) –> exporting a page to an output stream –> freeing memory –> loading the next page, and so on”.

The Aspose.Imaging currently supports batch export in the following formats:

  • For source images: Tiff, Djvu (i.e. only TiffImage and DjvuImage can be processed in batch export mode);
  • In image exporters: Tiff, Gif, Apng, Dicom, WebP.

In this way batch exports are currently supported in the following combinations:

  • from Tiff to Tiff;
  • from Tiff to Gif;
  • from Tiff to Apng;
  • from Tiff to Dicom;
  • from Tiff to WebP;
  • from Djvu to Tiff;
  • from Djvu to Gif;
  • from Djvu to Apng;
  • from Djvu to Dicom;
  • from Djvu to WebP.

  Load and create of WebP images can be proceeded using memory strategy optimization - i.e. limiting memory buffer size for operation.

import com.aspose.imaging.Image;
import com.aspose.imaging.PageExportingAction;
import com.aspose.imaging.RasterImage;
import com.aspose.imaging.fileformats.tiff.TiffImage;
import com.aspose.imaging.imageoptions.WebPOptions;
try (TiffImage tiffImage = (TiffImage) Image.load("10MB_Tif.tif"))
{
// Set batch operation for pages
tiffImage.setPageExportingAction(new PageExportingAction()
{
@Override
public void invoke(int pageIndex, Image page)
{
// Fires garbage collection to avoid unnecessary garbage storage from previous pages
System.gc();
((RasterImage)page).rotate(90);
}
});
tiffImage.save("rotated.webp", new WebPOptions());
/* Attention! In batch mode all pages will be released in this line!
If you want to further perform operations on the original image, you should reload it from the source to another instance. */
}