导出epub时,图片使用LazyResource来避免OOM

pull/957/head
ag2s20150909 4 years ago
parent 8a9f742749
commit a4ffeea3d5
  1. 2
      app/src/main/java/io/legado/app/help/BookHelp.kt
  2. 12
      app/src/main/java/io/legado/app/ui/book/cache/CacheViewModel.kt
  3. 38
      epublib/src/main/java/me/ag2s/epublib/domain/FileResourceProvider.java
  4. 1
      epublib/src/main/java/me/ag2s/epublib/util/IOUtil.java

@ -113,7 +113,7 @@ object BookHelp {
)
}
private fun getImageSuffix(src: String): String {
fun getImageSuffix(src: String): String {
var suffix = src.substringAfterLast(".").substringBefore(",")
if (suffix.length > 5) {
suffix = ".jpg"

@ -24,7 +24,6 @@ import me.ag2s.epublib.epub.EpubWriter
import me.ag2s.epublib.util.ResourceUtil
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.charset.Charset
@ -184,6 +183,7 @@ class CacheViewModel(application: Application) : BaseViewModel(application) {
}
}
private fun exportEpub(file: File, book: Book) {
val filename = "${book.name} by ${book.author}.epub"
val epubBook = EpubBook()
@ -254,9 +254,12 @@ class CacheViewModel(application: Application) : BaseViewModel(application) {
}
private fun setPic(src: String, book: Book, epubBook: EpubBook) {
val href = "${MD5Utils.md5Encode16(src)}${BookHelp.getImageSuffix(src)}"
val vFile = BookHelp.getImage(book, src)
val fp = FileResourceProvider(vFile.parent)
if (vFile.exists()) {
val img = Resource(FileInputStream(vFile), MD5Utils.md5Encode16(src) + ".jpg")
val img = LazyResource(fp, href)
epubBook.resources.add(img)
}
}
@ -275,7 +278,10 @@ class CacheViewModel(application: Application) : BaseViewModel(application) {
matchResult.groupValues[1].let {
val src = NetworkUtils.getAbsoluteURL(chapter.url, it)
setPic(src, book, epubBook)
text1 = text1.replace(src, MD5Utils.md5Encode16(src) + ".jpg")
text1 = text1.replace(
src,
"${MD5Utils.md5Encode16(src)}${BookHelp.getImageSuffix(src)}"
)
}
}

@ -0,0 +1,38 @@
package me.ag2s.epublib.domain;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 用于创建epub添加大文件如大量图片时容易OOM使用LazyResource避免OOM.
*
*/
public class FileResourceProvider implements LazyResourceProvider {
//需要导入资源的父目录
String dir;
/**
* 创建一个文件夹里面文件夹的LazyResourceProvider用于LazyResource
* @param dir 文件的目录
*/
public FileResourceProvider(String dir) {
this.dir = dir;
}
/**
* 创建一个文件夹里面文件夹的LazyResourceProvider用于LazyResource
* @param dirfile 文件夹
*/
@SuppressWarnings("unused")
public FileResourceProvider(File dirfile) {
this.dir = dirfile.getPath();
}
@Override
public InputStream getResourceStream(String href) throws IOException {
return new FileInputStream(new File(dir, href));
}
}

@ -450,6 +450,7 @@ public class IOUtil {
output.write(buffer, 0, n);
count += n;
}
input.close();
}
return count;
}

Loading…
Cancel
Save