Android: файл Epub не показывает изображения в эмуляторе / устройстве Android - PullRequest
4 голосов
/ 03 апреля 2012

Я использую http://www.siegmann.nl/epublib для чтения файла epub. Мой код указан ниже.

try {
    book = epubReader.readEpub(new FileInputStream("/sdcard/EpubTesting.epub"));

        Resource res;
        Spine contents = book.getSpine();

        List<SpineReference> spinelist  =  contents.getSpineReferences();
        StringBuilder string = new StringBuilder();
        String line = null;
        int count = spinelist.size();


         for (int i=0;i<count;i++){
            res = contents.getResource(i);
            try {
            InputStream is = res.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));

            try {
                while ((line = reader.readLine()) != null) {
                      linez = (string.append(line+"\n")).toString();
                }

            } catch (IOException e) {e.printStackTrace();}
        } catch (IOException e) {
            e.printStackTrace();
        }
         }


         System.out.println(linez);
         s1.loadDataWithBaseURL("/sdcard/",linez, "text/html", "UTF-8",null);

    }catch (FileNotFoundException e) {

        Toast.makeText(mContext, "File not found.", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        Toast.makeText(mContext, "IO Exception.", Toast.LENGTH_SHORT).show();
    }

Также пробовал

s1.loadDataWithBaseURL("",linez, "text/html", "UTF-8",null);
s1.loadDataWithBaseURL("file://mnt/sdcard/",linez, "text/html", "UTF-8",null);

Но результат - сифар. Пожалуйста, скажите мне, что я должен сделать, чтобы показать содержащиеся в файле изображения. Я прошел через часто задаваемые вопросы: «Создайте подкласс android.webkit.WebView», который перегружает метод «1010 *» таким образом, что он загружает изображение из Книги, а не из Интернета. Но пока я не знаю, где они извлекают файл, как я могу найти путь. Пожалуйста, скажите мне. Я очень смущен. Заранее спасибо.

Ответы [ 2 ]

15 голосов
/ 25 ноября 2013
public class EpubBookContentActivity extends Activity{

private static final String TAG = "EpubBookContentActivity";
WebView webview;

Book book;

int position = 0;

String line;
int i = 0;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content);

    webview = (WebView) findViewById(R.id.webView);
    webview.getSettings().setJavaScriptEnabled(true);

    AssetManager assetManager = getAssets();
    String[] files;

    try {

        files = assetManager.list("books");
        List<String> list =Arrays.asList(files);

        if (!this.makeDirectory("books")) {
            debug("faild to make books directory");
        }

        copyBookToDevice(list.get(position));

        String basePath = Environment.getExternalStorageDirectory() + "/books/";

        InputStream epubInputStream = assetManager.open("books/"+list.get(position));

        book = (new EpubReader()).readEpub(epubInputStream);

        DownloadResource(basePath);

        String linez = "";
        Spine spine = book.getSpine(); 
        List<SpineReference> spineList = spine.getSpineReferences() ;
        int count = spineList.size();

        StringBuilder string = new StringBuilder();
        for (int i = 0; count > i; i++) {

            Resource res = spine.getResource(i);

            try {
                InputStream is = res.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                try {
                    while ((line = reader.readLine()) != null) {
                        linez =   string.append(line + "\n").toString();
                    }

                } catch (IOException e) {e.printStackTrace();}


            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        linez = linez.replace("../", "");

//            File file = new File(Environment.getExternalStorageDirectory(),"test.html");
//            file.createNewFile();
//            FileOutputStream fileOutputStream = new FileOutputStream(file);
//            fileOutputStream.write(linez.getBytes());
//            fileOutputStream.close();


        webview.loadDataWithBaseURL("file://"+Environment.getExternalStorageDirectory()+"/books/", linez, "text/html", "utf-8", null);

    } catch (IOException e) {
        Log.e("epublib exception", e.getMessage());
    } 
}

public boolean makeDirectory(String dirName) {
    boolean res;        

    String filePath = new String(Environment.getExternalStorageDirectory()+"/"+dirName);

    debug(filePath);
    File file = new File(filePath);
    if (!file.exists()) {
        res = file.mkdirs();
    }else {
        res = false;        
    }
    return res; 
}

public void debug(String msg) {
    //      if (Setting.isDebug()) {
    Log.d("EPub", msg);
    //      }
}

public void copyBookToDevice(String fileName) {     
    System.out.println("Copy Book to donwload folder in phone");
    try
    {
        InputStream localInputStream = getAssets().open("books/"+fileName);
        String path = Environment.getExternalStorageDirectory() + "/books/"+fileName;
        FileOutputStream localFileOutputStream = new FileOutputStream(path);

        byte[] arrayOfByte = new byte[1024];
        int offset;
        while ((offset = localInputStream.read(arrayOfByte))>0)
        {
            localFileOutputStream.write(arrayOfByte, 0, offset);                  
        }
        localFileOutputStream.close();
        localInputStream.close();
        Log.d(TAG, fileName+" copied to phone");   

    }
    catch (IOException localIOException)
    {
        localIOException.printStackTrace();
        Log.d(TAG, "failed to copy");
        return;
    }
}



private void DownloadResource(String directory) {
    try {

        Resources rst = book.getResources();
        Collection<Resource> clrst = rst.getAll();
        Iterator<Resource> itr = clrst.iterator();

        while (itr.hasNext()) {
            Resource rs = itr.next();

            if ((rs.getMediaType() == MediatypeService.JPG)
                                            || (rs.getMediaType() == MediatypeService.PNG)
                                            || (rs.getMediaType() == MediatypeService.GIF)) {

                Log.d(TAG, rs.getHref());

                File oppath1 = new File(directory, rs.getHref().replace("OEBPS/", ""));    

                oppath1.getParentFile().mkdirs();
                oppath1.createNewFile();

                System.out.println("Path : "+oppath1.getParentFile().getAbsolutePath());


                FileOutputStream fos1 = new FileOutputStream(oppath1);
                fos1.write(rs.getData());
                fos1.close();

            } else if (rs.getMediaType() == MediatypeService.CSS) {

                File oppath = new File(directory, rs.getHref());

                oppath.getParentFile().mkdirs();
                oppath.createNewFile();

                FileOutputStream fos = new FileOutputStream(oppath);
                fos.write(rs.getData());
                fos.close();

            }

        }


    } catch (Exception e) {

    }
}
}
3 голосов
/ 12 июня 2012

Для этого вам необходимо загрузить все ресурсы файлов epub (например, изображения, таблицу стилей) в место, где вы загрузили файл .epub в SDCard.пожалуйста, проверьте код ниже, чтобы загрузить изображения и CSS-файлы из файлов .epub, используя epublib.для этого вам нужно отправить параметр объектов File, в который вы хотите сохранить эти изображения.

private void DownloadResource(File FileObj,String filename) {
  try {
   InputStream epubis = new FileInputStream(FileObj);
   book = (new EpubReader()).readEpub(epubis);

   Resources rst = book.getResources();
   Collection<Resource> clrst = rst.getAll();
   Iterator<Resource> itr = clrst.iterator();

   while (itr.hasNext()) {
    Resource rs = itr.next();

    if ((rs.getMediaType() == MediatypeService.JPG)
      || (rs.getMediaType() == MediatypeService.PNG)
      || (rs.getMediaType() == MediatypeService.GIF)) {
     File oppath1 = new File(directory, "Images/"
       + rs.getHref().replace("Images/", ""));

     oppath1.getParentFile().mkdirs();
     oppath1.createNewFile();

     FileOutputStream fos1 = new FileOutputStream(oppath1);
     fos1.write(rs.getData());
     fos1.close();

    } else if (rs.getMediaType() == MediatypeService.CSS) {
     File oppath = new File(directory, "Styles/"
       + rs.getHref().replace("Styles/", ""));

     oppath.getParentFile().mkdirs();
     oppath.createNewFile();

     FileOutputStream fos = new FileOutputStream(oppath);
     fos.write(rs.getData());
     fos.close();

    }

   }


  } catch (Exception e) {
   Log.v("error", e.getMessage());
  }
 }

после этого используйте этот код для установки пути изображений в веб-просмотре.если хранится на SD-карте, то

s1.loadDataWithBaseURL("file:///sdcard/",linez, "text/html",null,null);

или

s1.loadDataWithBaseURL("file://mnt/sdcard/",linez, "text/html", "UTF-8",null);

, если во внутренней памяти, то

s1.loadDataWithBaseURL("file:///data/data/com.example.project/app_mydownload/",linez, "text/html",null,null);
...