在Android中将图像保存到SD卡

时间:2013-12-19 15:12:22

标签: android android-intent android-sdcard

我只能保存1张图片,此代码会保存最后拍摄的图像,并保留相同名称,以便自动删除旧图像。我应该将大量图像存储到SD卡中,我应该怎么做才能修复此代码?

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == IMAGE_ACTION_CODE) {
        // 2
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        imagev.setImageBitmap(thumbnail);
        // 3
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        // 4

        String filename;
        Date date = new Date(0);
        SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMMddHHmmss");
        filename =  sdf.format(date);
        File file = new    

        File(Environment.getExternalStorageDirectory()+File.separator+filename+".jpg");

        try {
            file.createNewFile();
            FileOutputStream fo = new FileOutputStream(file);
            // 5
            fo.write(bytes.toByteArray());
            fo.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

我尝试了这段代码,但仍然在logcat中出错:

sdf.setTimeZone(TimeZone.getTimeZone("UTC")); filename = sdf.format(new Date());

我意识到这个问题与日期格式无关。

仍然在logcat中出错,例如:

  12-20 08:48:32.120: E/SoundPool(288): error loading /system/media/audio/ui/Lock.ogg
12-20 08:48:32.120: E/SoundPool(288): error loading /system/media/audio/ui/Unlock.ogg
12-20 08:48:32.620: E/EventHub(288): could not get driver version for /dev/input/mouse0, Not a typewriter
12-20 08:48:32.620: E/EventHub(288): could not get driver version for /dev/input/mice, Not a typewriter
12-20 08:48:32.720: E/Trace(288): error opening trace file: No such file or directory (2)
12-20 08:48:33.800: E/CommandListener(34): Failed to open /proc/sys/net/ipv6/conf/wlan0/disable_ipv6: No such file or directory
12-20 08:48:33.840: E/WifiStateMachine(288): Failed to disable IPv6: java.lang.IllegalStateException: command '1 interface ipv6 wlan0 disable' failed with '400 1 Failed to change IPv6 state (No such file or directory)'
12-20 08:48:33.920: E/MobileDataStateTracker(288): default: Ignoring feature request because could not acquire PhoneService
12-20 08:48:33.920: E/MobileDataStateTracker(288): default: Could not enable APN type "default"
12-20 08:48:36.850: E/Trace(349): error opening trace file: No such file or directory (2)
12-20 08:48:38.330: D/dalvikvm(288): GC_CONCURRENT freed 273K, 9% free 4588K/5012K, paused 8ms+31ms, total 516ms
12-20 08:48:38.330: D/dalvikvm(288): WAIT_FOR_CONCURRENT_GC blocked 284ms
12-20 08:48:38.340: D/dalvikvm(288): WAIT_FOR_CONCURRENT_GC blocked 335ms
12-20 08:48:38.350: D/dalvikvm(288): WAIT_FOR_CONCURRENT_GC blocked 317ms
12-20 08:48:38.350: I/ActivityManager(288): Start proc com.android.inputmethod.latin for service com.android.inputmethod.latin/.LatinIME: pid=377 uid=10018 gids={50018}
12-20 08:48:38.360: D/dalvikvm(288): WAIT_FOR_CONCURRENT_GC blocked 254ms
12-20 08:48:38.590: E/Trace(377): error opening trace file: No such file or directory (2)
12-20 08:48:39.500: E/ThrottleService(288): problem during onPollAlarm: java.lang.IllegalStateException: problem parsing stats: java.io.FileNotFoundException: /proc/net/xt_qtaguid/iface_stat_all: open failed: ENOENT (No such file or directory)
12-20 08:48:40.261: E/Trace(394): error opening trace file: No such file or directory (2)
12-20 08:48:42.171: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
12-20 08:48:42.331: E/ActivityThread(377): Failed to find provider info for com.android.inputmethod.latin.dictionarypack
12-20 08:48:42.502: E/BinaryDictionaryGetter(377): Could not find a dictionary pack
12-20 08:48:43.362: I/ActivityManager(288): Start proc android.process.acore for content provider com.android.providers.userdictionary/.UserDictionaryProvider: pid=432 uid=10010 gids={50010, 3003, 1015, 1028}
12-20 08:48:43.471: E/StrictMode(377): A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
12-20 08:48:43.471: E/StrictMode(377): java.lang.Throwable: Explicit termination method 'close' not called
12-20 08:48:43.471: E/StrictMode(377):  at dalvik.system.CloseGuard.open(CloseGuard.java:184)
12-20 08:48:43.471: E/StrictMode(377):  at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:412)
12-20 08:48:43.471: E/StrictMode(377):  at android.content.res.AssetManager.openNonAssetFdNative(Native Method)
12-20 08:48:43.471: E/StrictMode(377):  at android.content.res.AssetManager.openNonAssetFd(AssetManager.java:428)

并在错误日志中记录此错误:

**警告:未设置环境变量home。以下目录将用于存储Git。 警告:未处理的事件循环异常。

警告:EGit无法检测到安装路径&#34; gitPrefix&#34;本土的Git。因此,EGit不能尊重系统级别 可以在**

中配置的Git设置

2 个答案:

答案 0 :(得分:1)

Date date = new Date(0);

这会创建一个Date对象,自1970年1月1日,00:00:00 UTC时起为0毫秒。

你可能想要

Date date = new Date();

使用当前日期和时间创建Date对象。


logcat java.lang.Throwable: Explicit termination method 'close' not called中的异常是因为某些结果你还没有关闭你打开的文件。至少你应该改变

try {
    file.createNewFile();
    FileOutputStream fo = new FileOutputStream(file);
    // 5
    fo.write(bytes.toByteArray());
    fo.close();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

类似

FileOutputStream fo = null;
try {
    file.createNewFile();
    fo = new FileOutputStream(file);
    // 5
    fo.write(bytes.toByteArray());
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} finally {
    if (fo != null) {
        try { fo.close(); } catch (IOException ignore) {}
    }
}

所以FileOutputStream无论如何都会被关闭。

答案 1 :(得分:0)

在您的代码中,SimpleDateFormat以黄色下划线。你看到这个Lint:

  

要获取本地格式,请使用getDateInstance(),getDateTimeInstance()或getTimeInstance(),或使用新的SimpleDateFormat(字符串模板,Locale语言环境),例如Locale.US用于ASCII日期。

这意味着,你错过了一个拥有正确时间的论据 请参阅this answer,然后尝试以下代码:

String filename;
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMMddHHmmss", java.util.Locale.getDefault());
filename =  sdf.format(date); 

或者使用Locale.UK代替java.util.Locale.getDefault()或此处列表中的内容:Locale Documentation

希望这有帮助。