当我尝试保存图像时,为什么会出现NullPointerException?

时间:2012-10-23 15:06:04

标签: java google-app-engine persistence blobstore object-persistence

我正在尝试在我的应用中保存图片。但是当我试图保持图像对象时,我得到空指针异常。这是我的Image类:

 @PersistenceCapable
 public class ImageObject {

     @PrimaryKey
     @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
     private Key key;

     @Persistent
     private String title;

     @Persistent
     private Blob image;

     public ImageObject(){}

 //     all getters and setters
 }

以下是我的servlet代码,它提供了异常:

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
    List<BlobKey> blobKeyList = blobs.get("upload_img_form_input");
    BlobKey blobKey = blobKeyList.get(0);
    String keyString = req.getParameter("upload_img_form_key");

    Key key = KeyFactory.createKey(ImageObject.class.getSimpleName(), keyString);
    Image img = ImagesServiceFactory.makeImageFromBlob(blobKey);
    ImageObject imgObj = new ImageObject();
    imgObj.setKey(key);
    imgObj.setTitle(keyString);
    imgObj.setImage(img.getImageData());
// i am getting exception at this line where i am trying to persist 
    pm.makePersistent(imgObj);

任何人都可以告诉我为什么我得到这个NullPointerException?提前谢谢。

2 个答案:

答案 0 :(得分:0)

你可以在这条线上拥有Npe的唯一方法:

pm.makePersistent(imgObj);

是pm为空时

你应该检查那部分:

PersistenceManager pm = PMF.get().getPersistenceManager();

是classpath中的persistence.xml吗?

答案 1 :(得分:0)

根据我的经验,当您从img.getImageData()获取图片而不对其应用任何转换时,null会返回ImagesServiceFactory.makeImageFromBlob。如果你想从blob获取字节而不进行任何图像转换,你实际上并不需要图像服务,你只需要从blob存储中获取数据。我尝试了a blog post中的代码,效果很好。

public static byte[] readBlobFully(BlobKey blobKey) {

    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
    BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);

    if (blobInfo == null)
        return null;

    if (blobInfo.getSize() > Integer.MAX_VALUE)
        throw new RuntimeException("This method can only process blobs up to " + Integer.MAX_VALUE + " bytes");

    int blobSize = (int) blobInfo.getSize();
    int chunks = (int) Math.ceil(((double) blobSize / BlobstoreService.MAX_BLOB_FETCH_SIZE));
    int totalBytesRead = 0;
    int startPointer = 0;
    int endPointer;
    byte[] blobBytes = new byte[blobSize];

    for (int i = 0; i < chunks; i++) {

        endPointer = Math.min(blobSize - 1, startPointer + BlobstoreService.MAX_BLOB_FETCH_SIZE - 1);

        byte[] bytes = blobstoreService.fetchData(blobKey, startPointer, endPointer);

        for (int j = 0; j < bytes.length; j++)
            blobBytes[j + totalBytesRead] = bytes[j];

        startPointer = endPointer + 1;
        totalBytesRead += bytes.length;
    }

    return blobBytes;
}