@Test public void testBasicOperations() throws Exception { DefaultDiskStorage storage = getStorageSupplier(1).get(); final String resourceId1 = "R1"; final String resourceId2 = "R2"; // no file - get should fail BinaryResource resource1 = storage.getResource(resourceId1, null); Assert.assertNull(resource1); // write out the file now byte[] key1Contents = new byte[] {0, 1, 2}; writeToStorage(storage, resourceId1, key1Contents); // get should succeed now resource1 = storage.getResource(resourceId1, null); Assert.assertNotNull(resource1); File underlyingFile = ((FileBinaryResource) resource1).getFile(); Assert.assertArrayEquals(key1Contents, Files.toByteArray(underlyingFile)); // remove the file now - get should fail again Assert.assertTrue(underlyingFile.delete()); resource1 = storage.getResource(resourceId1, null); Assert.assertNull(resource1); // no file BinaryResource resource2 = storage.getResource(resourceId2, null); Assert.assertNull(resource2); }
/** * @param url 指定的url * @return 获取制定url的图片,需要保存为xx.jpg格式。 */ public File getFileFromDiskCache(String url) { File localFile = null; if (!TextUtils.isEmpty(url)) { CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(ImageRequest.fromUri(url), null); BinaryResource resource; if (ImagePipelineFactory.getInstance().getMainFileCache().hasKeySync(cacheKey)) { resource = ImagePipelineFactory.getInstance().getMainFileCache().getResource(cacheKey); localFile = ((FileBinaryResource) resource).getFile(); } else if (ImagePipelineFactory.getInstance().getSmallImageFileCache().hasKey(cacheKey)) { resource = ImagePipelineFactory.getInstance().getSmallImageFileCache().getResource(cacheKey); localFile = ((FileBinaryResource) resource).getFile(); } } return localFile; }
@Override protected File doInBackground(Void... params) { final String url = shot.getTeaserUrl(); try { ImageRequest imageRequest = ImageRequest.fromUri(url); CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(imageRequest); // ImagePipeline imagePipeline = Fresco.getImagePipeline(); // imagePipeline.prefetchToDiskCache(imageRequest,activity); BinaryResource resource = ImagePipelineFactory.getInstance().getMainDiskStorageCache().getResource(cacheKey); File file = ((FileBinaryResource) resource).getFile(); String fileName = url; fileName = fileName.substring(fileName.lastIndexOf('/') + 1); File renamed = new File(file.getParent(), fileName); if (!renamed.exists()) { FileUtil.copy(file, renamed); } return renamed; } catch (Exception ex) { Log.w("SHARE", "Sharing " + url + " failed", ex); return null; } }
@Override public String getCachePath(String uri) { if(VanGogh.isHttpUrl(uri)){ ///自己没摸索出来 // ImageRequest r = ImageRequestBuilder.newBuilderWithSource(Uri.parse(uri)).build(); // DiskStorageCache cache = Fresco.getImagePipelineFactory().getMainDiskStorageCache(); // CacheKey key = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(r); // if(cache.hasKey(key)){ // return cache.getResource(). // } ///网上找的方法,说是不推荐 FileBinaryResource resource = (FileBinaryResource)Fresco.getImagePipelineFactory() .getMainDiskStorageCache().getResource(new SimpleCacheKey(uri.toString())); File file = resource.getFile(); return file.getAbsolutePath(); }else{ return uri; } }
@Override public void viewImageMedia(int position, boolean loaded) { if(loaded){ PostItem item = getItem(position); CacheKey cacheKey = DefaultCacheKeyFactory.getInstance() .getEncodedCacheKey(ImageRequest .fromUri(Uri.parse(item.getUrl()))); if(cacheKey != null){ BinaryResource resource = ImagePipelineFactory.getInstance().getMainDiskStorageCache().getResource(cacheKey); File localFile; if(resource != null){ localFile = ((FileBinaryResource) resource).getFile(); Bundle bundle = new Bundle(); bundle.putString(getResources().getString(R.string.local_cache_key), localFile.getPath()); bundle.putString(getResources().getString(R.string.main_data_key), gson.toJson(item)); ((SlidingUpPanelActivity)context).setPanelView(Fragments.IMAGE_PREVIEW, bundle); } } } }
private void displayCachedImageFromBackgroundThread(ImageRequest request){ CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(ImageRequest.fromUri(request.getSourceUri())); if(cacheKey != null){ BinaryResource resource = ImagePipelineFactory.getInstance().getMainDiskStorageCache().getResource(cacheKey); if(resource != null){ File localFile = ((FileBinaryResource) resource).getFile(); if(localFile != null){ Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { imagePreview.setImage(ImageSource.uri(localFile.getPath())); } }); } } } }
@Override public BinaryResource getResource(String resourceId, Object debugInfo) { final File file = getContentFileFor(resourceId); if (file.exists()) { file.setLastModified(mClock.now()); return FileBinaryResource.createOrNull(file); } return null; }
@Override public long remove(Entry entry) { // it should be one entry return by us :) EntryImpl entryImpl = (EntryImpl) entry; FileBinaryResource resource = entryImpl.getResource(); return doRemove(resource.getFile()); }
private EntryImpl(String id, File cachedFile) { Preconditions.checkNotNull(cachedFile); this.id = Preconditions.checkNotNull(id); this.resource = FileBinaryResource.createOrNull(cachedFile); this.size = -1; this.timestamp = -1; }
@Override public BinaryResource commit(Object debugInfo) throws IOException { // the temp resource must be ours! File targetFile = getContentFileFor(mResourceId); try { FileUtils.rename(mTemporaryFile, targetFile); } catch (FileUtils.RenameException re) { CacheErrorLogger.CacheErrorCategory category; Throwable cause = re.getCause(); if (cause == null) { category = CacheErrorLogger.CacheErrorCategory.WRITE_RENAME_FILE_OTHER; } else if (cause instanceof FileUtils.ParentDirNotFoundException) { category = CacheErrorLogger.CacheErrorCategory.WRITE_RENAME_FILE_TEMPFILE_PARENT_NOT_FOUND; } else if (cause instanceof FileNotFoundException) { category = CacheErrorLogger.CacheErrorCategory.WRITE_RENAME_FILE_TEMPFILE_NOT_FOUND; } else { category = CacheErrorLogger.CacheErrorCategory.WRITE_RENAME_FILE_OTHER; } mCacheErrorLogger.logError( category, TAG, "commit", re); throw re; } if (targetFile.exists()) { targetFile.setLastModified(mClock.now()); } return FileBinaryResource.createOrNull(targetFile); }
private static FileBinaryResource writeToStorage( final DefaultDiskStorage storage, final String resourceId, final byte[] value) throws IOException { DiskStorage.Inserter inserter = storage.insert(resourceId, null); writeToResource(inserter, value); return (FileBinaryResource) inserter.commit(null); }
private static File write( DefaultDiskStorage storage, String resourceId, byte[] content) throws IOException { DiskStorage.Inserter inserter = storage.insert(resourceId, null); File file = ((DefaultDiskStorage.InserterImpl) inserter).mTemporaryFile; FileOutputStream fos = new FileOutputStream(file); try { fos.write(content); } finally { fos.close(); } return ((FileBinaryResource) inserter.commit(null)).getFile(); }
/** * 获取磁盘缓存的文件路径 * * @param url 文件url * @return 文件路径 */ private static String getDiskCacheFilePath(String url) { FileBinaryResource resource = (FileBinaryResource) Fresco.getImagePipelineFactory() .getMainFileCache() .getResource(new SimpleCacheKey(url)); // 防止中途清除磁盘缓存 导致获取不到 if (resource == null) { return ""; } File file = resource.getFile(); return file.getAbsolutePath(); }
private void save() { try { ImageRequest imageRequest = ImageRequest.fromUri(mUrl); CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(imageRequest); BinaryResource resource = ImagePipelineFactory.getInstance().getMainDiskStorageCache().getResource(cacheKey); File file = ((FileBinaryResource) resource).getFile(); String fileName = mUrl; fileName = fileName.substring(fileName.lastIndexOf('/') + 1); if (mTitle != null) { fileName = mTitle + fileName; } File pic = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); File dir = new File(pic, "material/"); if (!dir.exists()) { dir.mkdirs(); } File renamed = new File(dir, fileName); if (!renamed.exists()) { renamed.createNewFile(); FileUtil.copy(file, renamed); } UI.showToast(this, getString(R.string.image_saved_to, renamed.getAbsolutePath())); // Snackbar.make(mDraweeView,R.string.image_is_saved, Snackbar.LENGTH_LONG); } catch (Exception ex) { Log.w("SHARE", "Sharing " + mUrl + " failed", ex); } }
private File getCacheFile(final ImageRequest request) { FileCache mainFileCache = ImagePipelineFactory .getInstance() .getMainFileCache(); final CacheKey cacheKey = DefaultCacheKeyFactory .getInstance() .getEncodedCacheKey(request, false); // we don't need context, but avoid null File cacheFile = request.getSourceFile(); // http://crashes.to/s/ee10638fb31 if (mainFileCache.hasKey(cacheKey) && mainFileCache.getResource(cacheKey) != null) { cacheFile = ((FileBinaryResource) mainFileCache.getResource(cacheKey)).getFile(); } return cacheFile; }
/** * 本地缓存文件 */ public static File getCache(Context context, Uri uri) { if (!isCached(context, uri)) return null; ImageRequest imageRequest = ImageRequest.fromUri(uri); CacheKey cacheKey = DefaultCacheKeyFactory.getInstance() .getEncodedCacheKey(imageRequest, context); BinaryResource resource = ImagePipelineFactory.getInstance() .getMainFileCache().getResource(cacheKey); File file = ((FileBinaryResource) resource).getFile(); return file; }
private File getCacheFile(final ImageRequest request) { FileCache mainFileCache = ImagePipelineFactory .getInstance() .getMainFileCache(); final CacheKey cacheKey = DefaultCacheKeyFactory .getInstance() .getEncodedCacheKey(request, false); // we don't need context, but avoid null File cacheFile = request.getSourceFile(); if (mainFileCache.hasKey(cacheKey)) { cacheFile = ((FileBinaryResource) mainFileCache.getResource(cacheKey)).getFile(); } return cacheFile; }
@Override public FileBinaryResource getResource() { return resource; }
@Override public BitmapRegionDecoder intercept(Chain chain) throws IOException { final Uri uri = chain.uri(); BitmapRegionDecoder decoder = chain.chain(uri); if (decoder != null){ return decoder; } if (UriUtil.isNetworkUri(uri)){ ImagePipeline imagePipeline = ImagePipelineFactory.getInstance().getImagePipeline(); ImageRequest request = ImageRequest.fromUri(uri); DataSource<CloseableReference<PooledByteBuffer>> dataSource = imagePipeline.fetchEncodedImage(request,null); try { CloseableReference<PooledByteBuffer> ref = DataSources.waitForFinalResult(dataSource); if (ref == null){ return null; } PooledByteBuffer result = ref.get(); if (BuildConfig.DEBUG) { Log.d("FrescoInterceptor", "从我这加载"); } try { InputStream inputStream = new PooledByteBufferInputStream(result); Closeables.closeQuietly(inputStream); return BitmapRegionDecoder.newInstance(inputStream,false); } catch (IOException e) { ImageRequest imageRequest=ImageRequest.fromUri(uri); CacheKey cacheKey= DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(imageRequest,null); BinaryResource resource = ImagePipelineFactory.getInstance().getMainFileCache().getResource(cacheKey); File file=((FileBinaryResource)resource).getFile(); if (BuildConfig.DEBUG) { Log.d("FrescoInterceptor", file.getName()); } return Interceptors.fixJPEGDecoder(file,e); } } catch (Throwable throwable) { if (BuildConfig.DEBUG) { Log.d("FrescoInterceptor", "intercept: 加载失败了"); } throwable.printStackTrace(); return null; } } return null; }