2013-01-24 141 views
0

我有一個存放用戶個人資料圖片的實體。爲了簡單起見,我簡單地存儲了服務URL。我允許我的用戶裁剪他們的圖像。爲此,我從服務URL獲取圖像並創建一個com.google.appengine.api.images.Image;該圖像沒有一個blob鍵,因爲它是從一個字節數組創建的。什麼是最簡單的方式來存儲這個圖像作爲一個blob並獲得服務的網址?從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()); 

回答

4

您可以write data to blobstore programmatically。我用這個小片段:

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); 
} 
+0

如何檢索Blobkey?在我得到Blobkey後,我應該將它作爲一個財產存儲嗎? – serj