gpt4 book ai didi

java - 从 url 创建图像并保存在数据存储中

转载 作者:行者123 更新时间:2023-12-01 18:54:37 25 4
gpt4 key购买 nike

我有一个保存用户个人资料图片的实体。为了简单起见,我只存储服务 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());

最佳答案

您可以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);
}

关于java - 从 url 创建图像并保存在数据存储中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14509389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com