簡體   English   中英

嘗試保存圖像時為什么會出現NullPointerException?

[英]Why am i getting NullPointerException when i try to save 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嗎? 提前致謝。

唯一的辦法就是在這條線上設置Npe:

pm.makePersistent(imgObj);

是pm為空時

您應該檢查該部分:

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

您的persistence.xml在classpath中?

以我的經驗,當您從ImagesServiceFactory.makeImageFromBlob獲取圖像而未對其進行任何轉換時, img.getImageData()返回null 如果要從Blob獲取字節而不進行任何圖像轉換,則實際上不需要圖像服務,而只需要從Blob存儲中獲取數據即可。 我從博客文章中嘗試了此代碼,並且效果很好。

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM