Android NullPointerException при копировании exif-тегов - PullRequest
2 голосов
/ 25 июля 2011

Я пытаюсь изменить размер изображения, эта часть завершена.Затем я пытаюсь скопировать теги exif в новый файл.Я использую ExifInterface для чтения тегов.Я знаю, что это интерфейс, а не объект.Но когда я пытаюсь использовать его для действительно большого размера изображения, я получаю NullPointerException.Я получаю эту ошибку не для всех изображений.

07-25 11:59:23.870: WARN/System.err(1362): java.lang.NullPointerException
07-25 11:59:23.870: WARN/System.err(1362):     at android.media.ExifInterface.saveAttributes(ExifInterface.java:202)

Как ее решить?

Код для копирования EXIF-информации

try {
    // copy paste exif information from original file to new
    // file
    ExifInterface oldexif = new ExifInterface(filePath);
    ExifInterface newexif = new ExifInterface(file.getPath());

    int build = Build.VERSION.SDK_INT;

    // From API 11
    if (build >= 11) {
        newexif.setAttribute("FNumber",
                oldexif.getAttribute("FNumber"));
        newexif.setAttribute("ExposureTime",
                oldexif.getAttribute("ExposureTime"));
        newexif.setAttribute("ISOSpeedRatings",
                oldexif.getAttribute("ISOSpeedRatings"));
    }
    // From API 9
    if (build >= 9) {
        newexif.setAttribute("GPSAltitude",
                oldexif.getAttribute("GPSAltitude"));
        newexif.setAttribute("GPSAltitudeRef",
                oldexif.getAttribute("GPSAltitudeRef"));
    }
    // From API 8
    if (build >= 8) {
        newexif.setAttribute("FocalLength",
                oldexif.getAttribute("FocalLength"));
        newexif.setAttribute("GPSDateStamp",
                oldexif.getAttribute("GPSDateStamp"));
        newexif.setAttribute("GPSProcessingMethod",
                oldexif.getAttribute("GPSProcessingMethod"));
        newexif.setAttribute("GPSTimeStamp",
                oldexif.getAttribute("GPSTimeStamp"));
    }
    newexif.setAttribute("DateTime",
            oldexif.getAttribute("DateTime"));
    newexif.setAttribute("Flash", oldexif.getAttribute("Flash"));
    newexif.setAttribute("GPSLatitude",
            oldexif.getAttribute("GPSLatitude"));
    newexif.setAttribute("GPSLatitudeRef",
            oldexif.getAttribute("GPSLatitudeRef"));
    newexif.setAttribute("GPSLongitude",
            oldexif.getAttribute("GPSLongitude"));
    newexif.setAttribute("GPSLongitudeRef",
            oldexif.getAttribute("GPSLongitudeRef"));

    // You need to update this with your new height width
    newexif.setAttribute("ImageLength",
            oldexif.getAttribute("ImageLength"));
    newexif.setAttribute("ImageWidth",
            oldexif.getAttribute("ImageWidth"));

    newexif.setAttribute("Make", oldexif.getAttribute("Make"));
    newexif.setAttribute("Model", oldexif.getAttribute("Model"));
    newexif.setAttribute("Orientation",
            oldexif.getAttribute("Orientation"));
    newexif.setAttribute("WhiteBalance",
            oldexif.getAttribute("WhiteBalance"));

    newexif.saveAttributes();

    Toast.makeText(getApplicationContext(),
            "Image resized & saved successfully",
            Toast.LENGTH_SHORT).show();
} catch (Exception e) {
    e.printStackTrace();
}

Дополнительная информация о полете:

Когда я пытаюсь прочитать оба файла, создается новый файл: enter image description here


Отладка просмотра на oldexif enter image description here


Отладка просмотрана newexif enter image description here


Тестирование изображения

http://vikaskanani.files.wordpress.com/2011/07/test.jpg


Использование эмулятора Android для SDK 2.1

Ответы [ 2 ]

3 голосов
/ 25 июля 2011

Вы передаете нулевое значение где-то в saveAttributes.

Отладка NullPointerExceptions очень проста, если у вас есть исходный код.

Ниже вы можете найти исходный код для ExifInterface для Android 2.1

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.1_r2/android/media/ExifInterface.java#ExifInterface

строка 202 содержит это:

sb.append(val.length() + " ");

Единственное, что здесь может быть нулевым, это val.(одно из значений, которые вы передаете в методе saveAttributes).

Я бы предложил дважды проверить значения, которые вы передаете этому значению, и следить за нулевыми значениями.

0 голосов
/ 09 декабря 2012

Лучшим подходом к копированию данных EXIF ​​является использование библиотеки Sanselan Android.ExifInterface имеет ошибки повреждения данных в некоторых версиях, а также обрабатывает ограниченное количество тегов EXIF.

Вот сообщение в блоге, в котором рассказывается о копировании данных EXIF ​​с использованием Sanselan и предоставляется пример кода: http://bricolsoftconsulting.com/copying-exif-metadata-using-sanselan/

...