我需要使用App Engine BlobStore检索上传图像的高度和宽度。为了找到我使用以下代码:
try {
Image im = ImagesServiceFactory.makeImageFromBlob(blobKey);
if (im.getHeight() == ht && im.getWidth() == wd) {
flag = true;
}
} catch (UnsupportedOperationException e) {
}
我可以上传图像并生成BlobKey,但是当将Blobkey传递给makeImageFromBlob()时,会产生以下错误:
java.lang.UnsupportedOperationException:没有可用的图像数据
如何解决此问题或直接从BlobKey找到图像高度和宽度的任何其他方法。
答案 0 :(得分:7)
Image上的大多数方法本身都会抛出UnsupportedOperationException。 所以我使用com.google.appengine.api.blobstore.BlobstoreInputStream.BlobstoreInputStream来操作blobKey中的数据。这是我可以获得图像宽度和高度的方式。
byte[] data = getData(blobKey);
Image im = ImagesServiceFactory.makeImage(data);
if (im.getHeight() == ht && im.getWidth() == wd) {}
private byte[] getData(BlobKey blobKey) {
InputStream input;
byte[] oldImageData = null;
try {
input = new BlobstoreInputStream(blobKey);
ByteArrayOutputStream bais = new ByteArrayOutputStream();
byte[] byteChunk = new byte[4096];
int n;
while ((n = input.read(byteChunk)) > 0) {
bais.write(byteChunk, 0, n);
}
oldImageData = bais.toByteArray();
} catch (IOException e) {}
return oldImageData;
}
答案 1 :(得分:4)
如果您可以使用Guava,则实施更容易遵循:
public static byte[] getData(BlobKey blobKey) {
BlobstoreInputStream input = null;
try {
input = new BlobstoreInputStream(blobKey);
return ByteStreams.toByteArray(input);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
Closeables.closeQuietly(input);
}
}
其余的保持不变。
答案 2 :(得分:0)
另一种可能性是对图像进行无用的转换(旋转0度)
Image oldImage = ImagesServiceFactory.makeImageFromFilename(### Filepath ###);
Transform transform = ImagesServiceFactory.makeRotate(0);
oldImage = imagesService.applyTransform(transform,oldImage);
在转换之后,你可能会获得宽度和宽度。预期的图像高度:
oldImage.getWidth();
即使这样可行,这种转变会对性能产生负面影响;)