Transforming An Image Using The ImagesService

Here’s a short code example demonstrating how to transform images using the images service. This code example resizes an image to dimensions of 100×100, figures out the MIME type of the image, and prepares to write the image data into a write channel (good for writing to Cloud Storage or another storage service).

The image_content object represents a byte[] array containing image data. This code snippet then creates two objects: image_mime (the MIME type for the resized image) and buffer (a ByteBuffer containing the resized image’s data, ready for writing to a write channel).

// Create the image from the byte array
Image image = ImagesServiceFactory.makeImage(image_content);
// Resize the image to 100x100
Transform resize = ImagesServiceFactory.makeResize(100, 100);
ImagesService images = ImagesServiceFactory.getImagesService();
image = images.applyTransform(resize, image);
//Figure out the format of the image, and build a mime type.
Image.Format format = image.getFormat();
String image_mime = "image/" + format.toString().toLowerCase();
ByteBuffer buffer = ByteBuffer.wrap(image.getImageData());

Serving URL For Images Stored In Cloud Storage

Creating a serving URL for images stored in GCS is slightly different than for images stored in the Blobstore. Here’s a code sample:

Bucket represents the name of your Google Cloud Storage bucket, and object represents the file name of the image (including extension).

    String bucket = "bucket_name";
    String object = "file_name_including_extension";

    //Get serving url
    String gs_blob_key = "/gs/" + bucket + "/" + object;
    BlobKey blob_key = BlobstoreServiceFactory.getBlobstoreService().createGsBlobKey(gs_blob_key);
    ServingUrlOptions serving_options = ServingUrlOptions.Builder.withBlobKey(blob_key);
    String serving_url = ImagesServiceFactory.getImagesService().getServingUrl(serving_options);
    System.out.println("Serving URL: " + serving_url);