Lumpy
Lumpy

Reputation: 3652

Create Image from url and save in datastore

I have an entity that holds the users profile picture. To keep things simple I simply store the serving URL. I am allowing my users to crop their image. To do this I get the image from the serving URL and create a com.google.appengine.api.images.Image; This image doesn't have a blob key since it was created from a byte array. What is the easiest way to store this image as a blob and get the serving url?

URL url = new URL(currentProfile.getProfilePictureUrl());
InputStream input = url.openStream();
byte[] byteArray = IOUtils.toByteArray(input);
Image newImage = ImagesServiceFactory.makeImage(byteArray);

int imageWidth = newImage.getWidth();
int imageHeight = newImage.getHeight();

ImagesService imagesService = ImagesServiceFactory.getImagesService();
float lx = (float)x/(float)imageWidth;
float ty =  (float)y/(float)imageHeight;
float rx = (float)x2/(float)imageWidth;
float by = (float)y2/(float)imageHeight;
Transform resize = ImagesServiceFactory.makeCrop(lx, ty, rx, by);

Image transImage = imagesService.applyTransform(resize, newImage);

BlobstoreService blobStoreService = BlobstoreServiceFactory.getBlobstoreService();

//This doesn't work because transImage.getBlobKey() is null
ServingUrlOptions options =  ServingUrlOptions.Builder.withBlobKey(transImage.getBlobKey());

Upvotes: 0

Views: 430

Answers (1)

Peter Knego
Peter Knego

Reputation: 80340

You can write data to blobstore programmatically. I use this little snippet:

private BlobKey saveToBlobstore(String contentType, String imageName, byte[] imageData) throws IOException {
    // Get a file service
    FileService fileService = FileServiceFactory.getFileService();

    // Create a new Blob file and set the name to contain ref to UserImage
    AppEngineFile file = fileService.createNewBlobFile(contentType, imageName);

    // Open a channel to write to it
    FileWriteChannel writeChannel = fileService.openWriteChannel(file, true);

    writeChannel.write(ByteBuffer.wrap(imageData));
    writeChannel.closeFinally();

    // return the BlobKey
    return fileService.getBlobKey(file);
}

Upvotes: 4

Related Questions