Search in sources :

Example 6 with ImageInfo

use of com.github.hmdev.info.ImageInfo in project AozoraEpub3 by hmdev.

the class Epub3Writer method write.

/** epubファイルを出力
	 * @param converter 青空文庫テキスト変換クラス 画像のみの場合と切り替えて利用する
	 * @param src 青空文庫テキストファイルの入力Stream
	 * @param srcFile 青空文庫テキストファイル zip時の画像取得用
	 * @param zipTextFileName zipの場合はzip内のテキストファイルのパス付きファイル名
	 * @param epubFile 出力ファイル .epub拡張子
	 * @param bookInfo 書籍情報と縦横書き指定
	 * @param zipImageFileInfos zipの場合はzip内画像の情報 key=サブフォルダ付きの画像ファイル名
	 * @throws IOException */
public void write(AozoraEpub3Converter converter, BufferedReader src, File srcFile, String srcExt, File epubFile, BookInfo bookInfo, ImageInfoReader imageInfoReader) throws Exception {
    try {
        this.canceled = false;
        this.bookInfo = bookInfo;
        this.imageInfoReader = imageInfoReader;
        //インデックス初期化
        this.sectionIndex = 0;
        this.imageIndex = 0;
        this.sectionInfos.clear();
        this.chapterInfos.clear();
        this.vecGaijiInfo.clear();
        this.gaijiNameSet.clear();
        this.imageInfos.clear();
        this.outImageFileNames.clear();
        //Velocity用 共通コンテキスト設定
        this.velocityContext = new VelocityContext();
        //IDはタイトル著作者のハッシュで適当に生成
        String title = bookInfo.title == null ? "" : bookInfo.title;
        String creator = bookInfo.creator == null ? "" : bookInfo.creator;
        if ("".equals(bookInfo.creator))
            bookInfo.creator = null;
        //固有ID
        velocityContext.put("identifier", UUID.nameUUIDFromBytes((title + "-" + creator).getBytes()));
        //表紙の目次表示名
        velocityContext.put("cover_name", "表紙");
        //タイトル &<>はエスケープ
        velocityContext.put("title", CharUtils.escapeHtml(title));
        //タイトル読み &<>はエスケープ
        if (bookInfo.titleAs != null)
            velocityContext.put("titleAs", CharUtils.escapeHtml(bookInfo.titleAs));
        //著者 &<>はエスケープ
        velocityContext.put("creator", CharUtils.escapeHtml(creator));
        //著者読み &<>はエスケープ
        if (bookInfo.creatorAs != null)
            velocityContext.put("creatorAs", CharUtils.escapeHtml(bookInfo.creatorAs));
        //刊行者情報
        if (bookInfo.publisher != null)
            velocityContext.put("publisher", bookInfo.publisher);
        //書籍情報
        velocityContext.put("bookInfo", bookInfo);
        //更新日時
        velocityContext.put("modified", dateFormat.format(bookInfo.modified));
        //目次階層化
        velocityContext.put("navNest", this.navNest);
        //端末種別
        if (this.isKindle)
            velocityContext.put("kindle", true);
        //SVG画像出力
        if (this.isSvgImage)
            velocityContext.put("svgImage", true);
        //スタイル
        velocityContext.put("pageMargin", this.pageMargin);
        velocityContext.put("bodyMargin", this.bodyMargin);
        velocityContext.put("lineHeight", this.lineHeight);
        velocityContext.put("fontSize", this.fontSize);
        velocityContext.put("boldUseGothic", this.boldUseGothic);
        velocityContext.put("gothicUseBold", this.gothicUseBold);
        //出力先ePubのZipストリーム生成
        zos = new ZipArchiveOutputStream(new BufferedOutputStream(new FileOutputStream(epubFile)));
        //mimetypeは非圧縮
        //STOREDで格納しCRCとsizeを指定する必要がある
        ZipArchiveEntry mimeTypeEntry = new ZipArchiveEntry(MIMETYPE_PATH);
        FileInputStream fis = new FileInputStream(new File(templatePath + MIMETYPE_PATH));
        byte[] b = new byte[256];
        int len = fis.read(b);
        fis.close();
        CRC32 crc32 = new CRC32();
        crc32.update(b, 0, len);
        mimeTypeEntry.setMethod(ZipArchiveEntry.STORED);
        mimeTypeEntry.setCrc(crc32.getValue());
        mimeTypeEntry.setSize(len);
        zos.putArchiveEntry(mimeTypeEntry);
        zos.write(b, 0, len);
        b = null;
        zos.closeArchiveEntry();
        zos.setLevel(9);
        //テンプレートのファイルを格納
        for (String fileName : getTemplateFiles()) {
            writeFile(zos, fileName);
        }
        //サブパスの文字長
        int archivePathLength = 0;
        if (this.bookInfo.textEntryName != null)
            archivePathLength = this.bookInfo.textEntryName.indexOf('/') + 1;
        //zip出力用Writer
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
        //本文を出力
        this.writeSections(converter, src, bw, srcFile, srcExt, zos);
        if (this.canceled)
            return;
        //外字のcssを格納
        velocityContext.put("vecGaijiInfo", this.vecGaijiInfo);
        //スタイルと外字のcssを格納
        if (bookInfo.vertical) {
            zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + CSS_PATH + VERTICAL_TEXT_CSS));
            bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
            Velocity.mergeTemplate(templatePath + OPS_PATH + CSS_PATH + VERTICAL_TEXT_CSS_VM, "UTF-8", velocityContext, bw);
            bw.flush();
            zos.closeArchiveEntry();
        } else {
            zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + CSS_PATH + HORIZONTAL_TEXT_CSS));
            bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
            Velocity.mergeTemplate(templatePath + OPS_PATH + CSS_PATH + HORIZONTAL_TEXT_CSS_VM, "UTF-8", velocityContext, bw);
            bw.flush();
            zos.closeArchiveEntry();
        }
        //表紙をテンプレート+メタ情報から生成 先に出力すると外字画像出力で表紙の順番が狂う
        if (!bookInfo.imageOnly && (bookInfo.titlePageType == BookInfo.TITLE_MIDDLE || bookInfo.titlePageType == BookInfo.TITLE_HORIZONTAL)) {
            String vmFilePath = templatePath + OPS_PATH + XHTML_PATH + TITLE_M_VM;
            if (bookInfo.titlePageType == BookInfo.TITLE_HORIZONTAL) {
                converter.vertical = false;
                vmFilePath = templatePath + OPS_PATH + XHTML_PATH + TITLE_H_VM;
            }
            //ルビと外字画像注記と縦中横注記(縦書きのみ)のみ変換する
            String line = bookInfo.getTitleText();
            if (line != null)
                velocityContext.put("TITLE", converter.convertTitleLineToEpub3(line));
            line = bookInfo.getSubTitleText();
            if (line != null)
                velocityContext.put("SUBTITLE", converter.convertTitleLineToEpub3(line));
            line = bookInfo.getOrgTitleText();
            if (line != null)
                velocityContext.put("ORGTITLE", converter.convertTitleLineToEpub3(line));
            line = bookInfo.getSubOrgTitleText();
            if (line != null)
                velocityContext.put("SUBORGTITLE", converter.convertTitleLineToEpub3(line));
            line = bookInfo.getCreatorText();
            if (line != null)
                velocityContext.put("CREATOR", converter.convertTitleLineToEpub3(line));
            line = bookInfo.getSubCreatorText();
            if (line != null)
                velocityContext.put("SUBCREATOR", converter.convertTitleLineToEpub3(line));
            line = bookInfo.getSeriesText();
            if (line != null)
                velocityContext.put("SERIES", converter.convertTitleLineToEpub3(line));
            line = bookInfo.getPublisherText();
            if (line != null)
                velocityContext.put("PUBLISHER", converter.convertTitleLineToEpub3(line));
            //package.opf内で目次前に出力
            zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + XHTML_PATH + TITLE_FILE));
            bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
            Velocity.mergeTemplate(vmFilePath, "UTF-8", velocityContext, bw);
            bw.flush();
            zos.closeArchiveEntry();
            velocityContext.put("title_page", true);
            //表題行を目次に出力するならtitle.xhtmlを追加 (本文内の行はchapterinfosに追加されていない)
            ChapterLineInfo titleLineInfo = bookInfo.getChapterLineInfo(bookInfo.titleLine);
            if (titleLineInfo != null) {
                chapterInfos.add(0, new ChapterInfo("title", null, bookInfo.title, ChapterLineInfo.LEVEL_TITLE));
            }
        }
        if (this.canceled)
            return;
        //表紙データと表示の画像情報
        byte[] coverImageBytes = null;
        ImageInfo coverImageInfo = null;
        if (bookInfo.coverFileName != null && bookInfo.coverFileName.length() > 0) {
            //表紙情報をimageInfosに追加
            try {
                //表紙設定解除
                for (ImageInfo imageInfo2 : imageInfos) {
                    imageInfo2.setIsCover(false);
                }
                BufferedInputStream bis;
                if (bookInfo.coverFileName.startsWith("http")) {
                    bis = new BufferedInputStream(new URL(bookInfo.coverFileName).openStream(), 8192);
                } else {
                    bis = new BufferedInputStream(new FileInputStream(new File(bookInfo.coverFileName)), 8192);
                }
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                IOUtils.copy(bis, baos);
                coverImageBytes = baos.toByteArray();
                bis.close();
                baos.close();
                ByteArrayInputStream bais = new ByteArrayInputStream(coverImageBytes);
                coverImageInfo = ImageInfo.getImageInfo(bais);
                bais.close();
                String ext = coverImageInfo.getExt();
                if (isKindle || ext.equals("jpeg"))
                    ext = "jpg";
                coverImageInfo.setId("0000");
                coverImageInfo.setOutFileName("0000." + ext);
                if (!ext.matches("^(png|jpg|jpeg|gif)$")) {
                    LogAppender.println("表紙画像フォーマットエラー: " + bookInfo.coverFileName);
                    coverImageInfo = null;
                } else {
                    coverImageInfo.setIsCover(true);
                    this.imageInfos.add(0, coverImageInfo);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (bookInfo.coverImage != null) {
            //すべてのページの表紙設定解除
            for (ImageInfo imageInfo2 : imageInfos) {
                imageInfo2.setIsCover(false);
            }
            //プレビューでトリミングされた表紙
            String ext = "jpg";
            if (bookInfo.coverExt != null) {
                ext = bookInfo.coverExt;
            } else if (bookInfo.coverImageIndex > -1) {
                ImageInfo imageInfo = imageInfoReader.getImageInfo(bookInfo.coverImageIndex);
                if (imageInfo != null)
                    ext = imageInfo.getExt();
            }
            if (isKindle || ext.equals("jpeg"))
                ext = "jpg";
            coverImageInfo = ImageInfo.getImageInfo(ext, bookInfo.coverImage, -1);
            coverImageInfo.setId("0000");
            coverImageInfo.setOutFileName("0000." + ext);
            coverImageInfo.setIsCover(true);
            this.imageInfos.add(0, coverImageInfo);
        } else {
            //本文にないzip内の表紙を出力対象に追加 (テキストからの相対パス)
            if (bookInfo.coverImageIndex > -1 && imageInfoReader.countImageFileNames() > bookInfo.coverImageIndex) {
                if (!"txt".equals(srcExt)) {
                    String imageFileName = imageInfoReader.getImageFileName(bookInfo.coverImageIndex);
                    if (imageFileName != null) {
                        ImageInfo imageInfo = imageInfoReader.getImageInfo(imageFileName);
                        if (imageInfo != null) {
                            imageFileName = imageFileName.substring(archivePathLength);
                            outImageFileNames.add(imageFileName);
                            //表紙フラグも設定
                            for (ImageInfo imageInfo2 : imageInfos) {
                                imageInfo2.setIsCover(false);
                            }
                            imageInfo.setIsCover(true);
                            if (!this.imageInfos.contains(imageInfo))
                                this.imageInfos.add(imageInfo);
                        }
                    }
                }
            }
        }
        //表紙ページ出力 先頭画像表示時は画像出力時にカバー指定するので出力しない
        if (bookInfo.insertCoverPage) {
            //追加用の情報取得にのみ使う
            ImageInfo insertCoverInfo = coverImageInfo;
            if (insertCoverInfo == null && bookInfo.coverImageIndex > -1) {
                //本文中の挿絵の場合
                insertCoverInfo = imageInfoReader.getImageInfo(bookInfo.coverImageIndex);
                if (insertCoverInfo != null) {
                    insertCoverInfo.setIsCover(true);
                    if (!bookInfo.imageOnly && insertCoverInfo.getId() == null) {
                        //zip内の画像で追加処理されていない
                        this.imageIndex++;
                        String imageId = decimalFormat.format(this.imageIndex);
                        insertCoverInfo.setId(imageId);
                        String ext = insertCoverInfo.getExt();
                        if (isKindle)
                            ext = "jpg";
                        insertCoverInfo.setOutFileName(imageId + "." + ext);
                    }
                }
            }
            if (insertCoverInfo != null) {
                SectionInfo sectionInfo = new SectionInfo("cover-page");
                if (this.imageSizeType != SectionInfo.IMAGE_SIZE_TYPE_AUTO) {
                    //画像が横長なら幅100% それ以外は高さ100%
                    if ((double) insertCoverInfo.getWidth() / insertCoverInfo.getHeight() >= (double) this.coverW / this.coverH)
                        sectionInfo.setImageFitW(true);
                    else
                        sectionInfo.setImageFitH(true);
                } else {
                    sectionInfo.setImageFitW(false);
                    sectionInfo.setImageFitH(false);
                }
                this.velocityContext.put("sectionInfo", sectionInfo);
                this.velocityContext.put("coverImage", insertCoverInfo);
                zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + XHTML_PATH + COVER_FILE));
                bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
                Velocity.mergeTemplate(templatePath + OPS_PATH + XHTML_PATH + COVER_VM, "UTF-8", velocityContext, bw);
                bw.flush();
                zos.closeArchiveEntry();
            } else {
                //画像がなかったら表紙ページ無し
                bookInfo.insertCoverPage = false;
            }
        }
        //package.opf 出力
        velocityContext.put("sections", sectionInfos);
        velocityContext.put("images", imageInfos);
        zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + PACKAGE_FILE));
        bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
        Velocity.mergeTemplate(templatePath + OPS_PATH + PACKAGE_VM, "UTF-8", velocityContext, bw);
        bw.flush();
        zos.closeArchiveEntry();
        //nullを除去
        for (int i = chapterInfos.size() - 1; i >= 0; i--) {
            if (chapterInfos.get(i).getChapterName() == null)
                chapterInfos.remove(i);
        }
        //表題のレベルを2つめと同じにする
        if (bookInfo.insertTitleToc && chapterInfos.size() >= 2) {
            chapterInfos.get(0).chapterLevel = chapterInfos.get(1).chapterLevel;
        }
        //目次の階層情報を設定
        //レベルを0から開始に変更
        int[] chapterCounts = new int[10];
        for (ChapterInfo chapterInfo : chapterInfos) {
            chapterCounts[chapterInfo.getChapterLevel()]++;
        }
        int[] newLevel = new int[10];
        int level = 0;
        for (int i = 0; i < chapterCounts.length; i++) {
            if (chapterCounts[i] > 0)
                newLevel[i] = level++;
        }
        for (ChapterInfo chapterInfo : chapterInfos) {
            chapterInfo.chapterLevel = newLevel[chapterInfo.chapterLevel];
        }
        //開始終了情報を追加 nav用
        //レベル0
        ChapterInfo preChapterInfo = new ChapterInfo(null, null, null, 0);
        for (ChapterInfo chapterInfo : chapterInfos) {
            if (preChapterInfo != null) {
                //開始
                chapterInfo.levelStart = Math.max(0, chapterInfo.chapterLevel - preChapterInfo.chapterLevel);
                //終了
                preChapterInfo.levelEnd = Math.max(0, preChapterInfo.chapterLevel - chapterInfo.chapterLevel);
            }
            preChapterInfo = chapterInfo;
        }
        //一番最後は閉じる
        if (chapterInfos.size() > 0) {
            ChapterInfo chapterInfo = chapterInfos.lastElement();
            if (chapterInfo != null)
                chapterInfo.levelEnd = chapterInfo.chapterLevel;
        }
        int ncxDepth = 1;
        if (this.ncxNest) {
            int minLevel = 99;
            int maxLevel = 0;
            //navPointを閉じる回数をlevelEndに設定
            //navPointを開始したレベルidxに1を設定
            int[] navPointLevel = new int[10];
            preChapterInfo = null;
            for (ChapterInfo chapterInfo : chapterInfos) {
                if (preChapterInfo != null) {
                    int preLevel = preChapterInfo.chapterLevel;
                    int curLevel = chapterInfo.chapterLevel;
                    minLevel = Math.min(minLevel, curLevel);
                    maxLevel = Math.max(maxLevel, curLevel);
                    navPointLevel[preLevel] = 1;
                    if (preLevel < curLevel) {
                        //前より小さい場合
                        preChapterInfo.navClose = 0;
                    } else if (preLevel > curLevel) {
                        //前より大きい
                        int close = 0;
                        for (int i = curLevel; i < navPointLevel.length; i++) {
                            if (navPointLevel[i] == 1) {
                                close++;
                                navPointLevel[i] = 0;
                            }
                        }
                        preChapterInfo.navClose = close;
                    } else {
                        preChapterInfo.navClose = 1;
                        navPointLevel[preLevel] = 0;
                    }
                }
                preChapterInfo = chapterInfo;
            }
            if (minLevel < maxLevel)
                ncxDepth = maxLevel - minLevel + 1;
            //一番最後は閉じる
            if (chapterInfos.size() > 0) {
                ChapterInfo chapterInfo = chapterInfos.lastElement();
                if (chapterInfo != null) {
                    int close = 1;
                    for (int i = 0; i < navPointLevel.length; i++) {
                        if (navPointLevel[i] == 1) {
                            close++;
                        }
                    }
                    chapterInfo.navClose = close;
                }
            }
        }
        //velocityに設定 1~
        velocityContext.put("ncx_depth", ncxDepth);
        //出力前に縦中横とエスケープ処理
        if (!bookInfo.imageOnly) {
            converter.vertical = bookInfo.tocVertical;
            int spaceHyphenation = converter.getSpaceHyphenation();
            converter.setSpaceHyphenation(0);
            StringBuilder buf = new StringBuilder();
            for (ChapterInfo chapterInfo : chapterInfos) {
                buf.setLength(0);
                String converted = CharUtils.escapeHtml(chapterInfo.getChapterName());
                if (bookInfo.tocVertical) {
                    converted = converter.convertTcyText(converted);
                }
                chapterInfo.setChapterName(converted);
            }
            //戻す
            converter.vertical = bookInfo.vertical;
            converter.setSpaceHyphenation(spaceHyphenation);
        }
        //navファイル
        velocityContext.put("chapters", chapterInfos);
        zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + XHTML_PATH + XHTML_NAV_FILE));
        bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
        Velocity.mergeTemplate(templatePath + OPS_PATH + XHTML_PATH + XHTML_NAV_VM, "UTF-8", velocityContext, bw);
        bw.flush();
        zos.closeArchiveEntry();
        //tocファイル
        velocityContext.put("chapters", chapterInfos);
        zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + TOC_FILE));
        bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
        Velocity.mergeTemplate(templatePath + OPS_PATH + TOC_VM, "UTF-8", velocityContext, bw);
        bw.flush();
        zos.closeArchiveEntry();
        if (src != null)
            src.close();
        if (this.canceled)
            return;
        //プログレスバーにテキスト進捗分を追加
        if (this.jProgressBar != null && !bookInfo.imageOnly)
            this.jProgressBar.setValue(bookInfo.totalLineNum / 10);
        //フォントファイル格納
        if (!bookInfo.imageOnly) {
            File fontsPath = new File(templatePath + OPS_PATH + FONTS_PATH);
            if (fontsPath.exists()) {
                for (File fontFile : fontsPath.listFiles()) {
                    String outFileName = OPS_PATH + FONTS_PATH + fontFile.getName();
                    zos.putArchiveEntry(new ZipArchiveEntry(outFileName));
                    fis = new FileInputStream(new File(templatePath + outFileName));
                    IOUtils.copy(fis, zos);
                    fis.close();
                    zos.closeArchiveEntry();
                }
            }
        }
        //外字ファイル格納
        for (GaijiInfo gaijiInfo : this.vecGaijiInfo) {
            File gaijiFile = gaijiInfo.getFile();
            if (gaijiFile.exists()) {
                String outFileName = OPS_PATH + GAIJI_PATH + gaijiFile.getName();
                zos.putArchiveEntry(new ZipArchiveEntry(outFileName));
                fis = new FileInputStream(gaijiFile);
                IOUtils.copy(fis, zos);
                fis.close();
                zos.closeArchiveEntry();
            }
        }
        zos.setLevel(0);
        //表紙編集時のイメージ出力
        if (coverImageInfo != null) {
            try {
                //kindleの場合は常にjpegに変換
                if (isKindle) {
                    String imgExt = coverImageInfo.getExt();
                    if (!imgExt.startsWith("jp")) {
                        if (bookInfo.coverImage == null) {
                            ByteArrayInputStream bais = new ByteArrayInputStream(coverImageBytes);
                            bookInfo.coverImage = ImageUtils.readImage(imgExt, bais);
                            bais.close();
                        }
                        coverImageInfo.setExt("jpeg");
                    }
                }
                if (bookInfo.coverImage != null) {
                    //プレビューで編集されている場合
                    zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + IMAGES_PATH + coverImageInfo.getOutFileName()));
                    this.writeCoverImage(bookInfo.coverImage, zos, coverImageInfo);
                    zos.closeArchiveEntry();
                    //同じ画像が使われている場合は以後はファイルから読み込ませる
                    bookInfo.coverImage = null;
                } else {
                    ByteArrayInputStream bais = new ByteArrayInputStream(coverImageBytes);
                    zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + IMAGES_PATH + coverImageInfo.getOutFileName()));
                    this.writeCoverImage(bais, zos, coverImageInfo);
                    zos.closeArchiveEntry();
                    bais.close();
                }
                //カバー画像は出力済みなので削除
                imageInfos.remove(0);
                if (this.jProgressBar != null)
                    this.jProgressBar.setValue(this.jProgressBar.getValue() + 10);
            } catch (Exception e) {
                e.printStackTrace();
                LogAppender.error("表紙画像取得エラー: " + bookInfo.coverFileName);
            }
        }
        if (this.canceled)
            return;
        //本文画像出力 (画像のみの場合は出力済)
        if ("txt".equals(srcExt)) {
            //txtの場合はファイルシステムから取得
            for (String srcImageFileName : imageInfoReader.getImageFileNames()) {
                //拡張子修正
                srcImageFileName = imageInfoReader.correctExt(srcImageFileName);
                if (outImageFileNames.contains(srcImageFileName)) {
                    ImageInfo imageInfo = imageInfoReader.getImageInfo(srcImageFileName);
                    if (imageInfo == null) {
                        LogAppender.println("[WARN] 画像ファイルなし: " + srcImageFileName);
                    } else {
                        File imageFile = imageInfoReader.getImageFile(srcImageFileName);
                        if (imageFile.exists()) {
                            fis = new FileInputStream(imageFile);
                            zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + IMAGES_PATH + imageInfo.getOutFileName()));
                            this.writeImage(new BufferedInputStream(fis, 8192), zos, imageInfo);
                            zos.closeArchiveEntry();
                            fis.close();
                            outImageFileNames.remove(srcImageFileName);
                        }
                    }
                }
                if (this.canceled)
                    return;
                if (this.jProgressBar != null)
                    this.jProgressBar.setValue(this.jProgressBar.getValue() + 10);
            }
        } else if (!bookInfo.imageOnly) {
            if ("rar".equals(srcExt)) {
                ////////////////////////////////
                //Rar
                Archive archive = new Archive(srcFile);
                try {
                    for (FileHeader fileHeader : archive.getFileHeaders()) {
                        if (!fileHeader.isDirectory()) {
                            String entryName = fileHeader.getFileNameW();
                            if (entryName.length() == 0)
                                entryName = fileHeader.getFileNameString();
                            entryName = entryName.replace('\\', '/');
                            //アーカイブ内のサブフォルダは除外してテキストからのパスにする
                            String srcImageFileName = entryName.substring(archivePathLength);
                            if (outImageFileNames.contains(srcImageFileName)) {
                                InputStream is = archive.getInputStream(fileHeader);
                                try {
                                    this.writeArchiveImage(srcImageFileName, is);
                                } finally {
                                    is.close();
                                }
                            }
                        }
                    }
                } finally {
                    archive.close();
                }
            } else {
                ////////////////////////////////
                //Zip
                ZipArchiveInputStream zis = new ZipArchiveInputStream(new BufferedInputStream(new FileInputStream(srcFile), 65536), "MS932", false);
                try {
                    ArchiveEntry entry;
                    while ((entry = zis.getNextZipEntry()) != null) {
                        //アーカイブ内のサブフォルダは除外してテキストからのパスにする
                        String srcImageFileName = entry.getName().substring(archivePathLength);
                        if (outImageFileNames.contains(srcImageFileName)) {
                            this.writeArchiveImage(srcImageFileName, zis);
                        }
                    }
                } finally {
                    zis.close();
                }
            }
        }
        //エラーがなければ100%
        if (this.jProgressBar != null)
            this.jProgressBar.setValue(this.jProgressBar.getMaximum());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            //ePub3出力ファイルを閉じる
            if (zos != null)
                zos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //メンバ変数解放
        this.velocityContext = null;
        this.bookInfo = null;
        this.imageInfoReader = null;
    }
}
Also used : ChapterInfo(com.github.hmdev.info.ChapterInfo) Archive(com.github.junrar.Archive) CRC32(java.util.zip.CRC32) VelocityContext(org.apache.velocity.VelocityContext) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) ArchiveEntry(org.apache.commons.compress.archivers.ArchiveEntry) URL(java.net.URL) BufferedWriter(java.io.BufferedWriter) BufferedInputStream(java.io.BufferedInputStream) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) ImageInfo(com.github.hmdev.info.ImageInfo) BufferedOutputStream(java.io.BufferedOutputStream) FileHeader(com.github.junrar.rarfile.FileHeader) ZipArchiveInputStream(org.apache.commons.compress.archivers.zip.ZipArchiveInputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) ZipArchiveInputStream(org.apache.commons.compress.archivers.zip.ZipArchiveInputStream) InputStream(java.io.InputStream) ChapterLineInfo(com.github.hmdev.info.ChapterLineInfo) ZipArchiveOutputStream(org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) SectionInfo(com.github.hmdev.info.SectionInfo) GaijiInfo(com.github.hmdev.info.GaijiInfo) File(java.io.File)

Example 7 with ImageInfo

use of com.github.hmdev.info.ImageInfo in project AozoraEpub3 by hmdev.

the class Epub3ImageWriter method getImageFilePath.

@Override
public String getImageFilePath(String srcImageFileName, int lineNum) {
    boolean isCover = false;
    //xhtmlと画像ファイル名の番号を合わせるため先に++
    this.imageIndex++;
    String ext = "";
    try {
        ext = srcImageFileName.substring(srcImageFileName.lastIndexOf('.') + 1).toLowerCase();
    } catch (Exception e) {
    }
    String imageId = decimalFormat.format(this.imageIndex);
    String imageFileName = IMAGES_PATH + imageId + "." + ext;
    ImageInfo imageInfo;
    try {
        imageInfo = this.imageInfoReader.getImageInfo(srcImageFileName);
        imageInfo.setId(imageId);
        imageInfo.setOutFileName(imageId + "." + ext);
        if (!imageInfo.getExt().matches("^(png|jpeg|gif|jpg)$")) {
            LogAppender.error(lineNum, "画像フォーマットエラー", srcImageFileName);
            return null;
        }
        if (this.imageIndex - 1 == bookInfo.coverImageIndex) {
            imageInfo.setIsCover(true);
            isCover = true;
        }
        this.imageInfos.add(imageInfo);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    //先頭に表紙ページ移動の場合でカバーページならnullを返して本文中から削除
    if (bookInfo.insertCoverPage && isCover)
        return null;
    return "../" + imageFileName;
}
Also used : IOException(java.io.IOException) ImageInfo(com.github.hmdev.info.ImageInfo) IOException(java.io.IOException) RarException(com.github.junrar.exception.RarException)

Example 8 with ImageInfo

use of com.github.hmdev.info.ImageInfo in project AozoraEpub3 by hmdev.

the class Epub3ImageWriter method startImageSection.

/** セクション開始. 
	 * @throws IOException */
private void startImageSection(String srcImageFilePath) throws IOException {
    this.sectionIndex++;
    String sectionId = decimalFormat.format(this.sectionIndex);
    //package.opf用にファイル名
    SectionInfo sectionInfo = new SectionInfo(sectionId);
    //画像専用指定
    sectionInfo.setImagePage(true);
    //画像サイズが横長なら幅に合わせる
    ImageInfo imageInfo = this.imageInfoReader.getImageInfo(srcImageFilePath);
    if (imageInfo != null) {
        if ((double) imageInfo.getWidth() / imageInfo.getHeight() >= (double) this.dispW / this.dispH) {
            if (this.rotateAngle != 0 && this.dispW < this.dispH && (double) imageInfo.getHeight() / imageInfo.getWidth() < (double) this.dispW / this.dispH) {
                //縦長画面で横長
                imageInfo.rotateAngle = this.rotateAngle;
                if (this.imageSizeType != SectionInfo.IMAGE_SIZE_TYPE_AUTO)
                    sectionInfo.setImageFitH(true);
            } else {
                //高さでサイズ調整する場合は高さの%指定
                if (this.imageSizeType == SectionInfo.IMAGE_SIZE_TYPE_HEIGHT)
                    sectionInfo.setImageHeight(((double) imageInfo.getHeight() / imageInfo.getWidth()) * ((double) this.dispW / this.dispH));
                else if (this.imageSizeType == SectionInfo.IMAGE_SIZE_TYPE_ASPECT)
                    sectionInfo.setImageFitW(true);
            }
        } else {
            if (this.rotateAngle != 0 && this.dispW > this.dispH && (double) imageInfo.getHeight() / imageInfo.getWidth() > (double) this.dispW / this.dispH) {
                //横長画面で縦長
                imageInfo.rotateAngle = this.rotateAngle;
                //高さでサイズ調整する場合は高さの%指定
                if (this.imageSizeType == SectionInfo.IMAGE_SIZE_TYPE_HEIGHT)
                    sectionInfo.setImageHeight(((double) imageInfo.getHeight() / imageInfo.getWidth()) * ((double) this.dispW / this.dispH));
                else if (this.imageSizeType == SectionInfo.IMAGE_SIZE_TYPE_ASPECT)
                    sectionInfo.setImageFitW(true);
            } else {
                if (this.imageSizeType != SectionInfo.IMAGE_SIZE_TYPE_AUTO)
                    sectionInfo.setImageFitH(true);
            }
        }
    }
    this.sectionInfos.add(sectionInfo);
    //目次追加
    if (this.sectionIndex == 1 || this.sectionIndex % 5 == 0)
        this.addChapter(null, "" + this.sectionIndex, 0);
    super.zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + XHTML_PATH + sectionId + ".xhtml"));
    //ヘッダ出力
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(super.zos, "UTF-8"));
    //出力開始するセクションに対応したSectionInfoを設定
    this.velocityContext.put("sectionInfo", sectionInfo);
    Velocity.getTemplate(this.templatePath + OPS_PATH + XHTML_PATH + XHTML_HEADER_VM).merge(this.velocityContext, bw);
    bw.flush();
}
Also used : ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) OutputStreamWriter(java.io.OutputStreamWriter) SectionInfo(com.github.hmdev.info.SectionInfo) ImageInfo(com.github.hmdev.info.ImageInfo) BufferedWriter(java.io.BufferedWriter)

Example 9 with ImageInfo

use of com.github.hmdev.info.ImageInfo in project AozoraEpub3 by hmdev.

the class Epub3Writer method writeArchiveImage.

/** アーカイブ内の画像を出力 */
void writeArchiveImage(String srcImageFileName, InputStream is) throws IOException {
    //拡張子修正
    srcImageFileName = imageInfoReader.correctExt(srcImageFileName);
    ImageInfo imageInfo = imageInfoReader.getImageInfo(srcImageFileName);
    //Zip内テキストの場合はidと出力ファイル名が登録されていなければ出力しない。
    if (imageInfo != null) {
        if (imageInfo.getId() != null) {
            //回転チェック
            if ((double) imageInfo.getWidth() / imageInfo.getHeight() >= (double) this.dispW / this.dispH) {
                if (this.rotateAngle != 0 && this.dispW < this.dispH && (double) imageInfo.getHeight() / imageInfo.getWidth() < (double) this.dispW / this.dispH) {
                    //縦長画面で横長
                    imageInfo.rotateAngle = this.rotateAngle;
                }
            } else {
                if (this.rotateAngle != 0 && this.dispW > this.dispH && (double) imageInfo.getHeight() / imageInfo.getWidth() > (double) this.dispW / this.dispH) {
                    //横長画面で縦長
                    imageInfo.rotateAngle = this.rotateAngle;
                }
            }
            zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + IMAGES_PATH + imageInfo.getOutFileName()));
            //Zip,Rarからの直接読み込みは失敗するので一旦バイト配列にする
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(new BufferedInputStream(is, 16384), baos);
            byte[] bytes = baos.toByteArray();
            baos.close();
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            this.writeImage(bais, zos, imageInfo);
            bais.close();
            zos.closeArchiveEntry();
        }
        if (this.canceled)
            return;
        if (this.jProgressBar != null)
            this.jProgressBar.setValue(this.jProgressBar.getValue() + 10);
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImageInfo(com.github.hmdev.info.ImageInfo)

Example 10 with ImageInfo

use of com.github.hmdev.info.ImageInfo in project AozoraEpub3 by hmdev.

the class Epub3Writer method getImagePageType.

/** 画像が単一ページ画像にできるかチェック
	 * @param srcFilePath テキスト内の画像相対パス文字列
	 * @throws IOException */
public int getImagePageType(String srcFilePath, int tagLevel, int lineNum, boolean hasCaption) {
    try {
        ImageInfo imageInfo = this.imageInfoReader.getImageInfo(srcFilePath);
        //拡張子修正
        if (imageInfo == null)
            imageInfo = this.imageInfoReader.getImageInfo(this.imageInfoReader.correctExt(srcFilePath));
        if (imageInfo == null)
            return PageBreakType.IMAGE_PAGE_NONE;
        float imageOrgWidth = imageInfo.getWidth();
        float imageOrgHeight = imageInfo.getHeight();
        float imageWidth = imageOrgWidth;
        float imageHeight = imageOrgHeight;
        if (this.imageScale > 0) {
            imageWidth *= imageScale;
            imageHeight *= imageScale;
        }
        //回り込みサイズ以下
        if (this.imageFloatType != 0 && (imageOrgWidth >= 64 || imageOrgHeight >= 64) && imageOrgWidth <= this.imageFloatW && imageOrgHeight <= this.imageFloatH) {
            if (this.imageFloatType == 1) {
                if (imageWidth > dispW)
                    return PageBreakType.IMAGE_INLINE_TOP_W;
                return PageBreakType.IMAGE_INLINE_TOP;
            } else {
                if (imageWidth > dispW)
                    return PageBreakType.IMAGE_INLINE_BOTTOM_W;
                return PageBreakType.IMAGE_INLINE_BOTTOM;
            }
        }
        //指定サイズ以下なら単ページ化 (タグ外かつキャプションが無い場合のみ)
        if (imageOrgWidth >= this.singlePageWidth || imageOrgWidth >= singlePageSizeW && imageOrgHeight >= singlePageSizeH) {
            if (tagLevel == 0) {
                if (!hasCaption) {
                    if (imageWidth <= this.dispW && imageHeight < this.dispH) {
                        //画面より小さい場合
                        if (!this.fitImage)
                            return PageBreakType.IMAGE_PAGE_NOFIT;
                    } else {
                        //画面より大きく、サイズ指定無し
                        if (this.imageSizeType == SectionInfo.IMAGE_SIZE_TYPE_AUTO)
                            return PageBreakType.IMAGE_PAGE_NOFIT;
                    }
                    //画面より横長
                    if (imageWidth / imageHeight > (double) this.dispW / this.dispH) {
                        if (this.rotateAngle != 0 && this.dispW < this.dispH && imageWidth > imageHeight * 1.1) {
                            //縦長画面で110%以上横長
                            imageInfo.rotateAngle = this.rotateAngle;
                            //回転後画面より横長
                            if (imageHeight / imageWidth > (double) dispW / dispH)
                                return PageBreakType.IMAGE_PAGE_W;
                            return PageBreakType.IMAGE_PAGE_H;
                        } else {
                            return PageBreakType.IMAGE_PAGE_W;
                        }
                    } else //画面より縦長
                    {
                        if (this.rotateAngle != 0 && this.dispW > this.dispH && imageWidth * 1.1 < imageHeight) {
                            //横長画面で110%以上縦長
                            imageInfo.rotateAngle = this.rotateAngle;
                            //回転後画面より横長
                            if (imageHeight / imageWidth > (double) dispW / dispH)
                                return PageBreakType.IMAGE_PAGE_W;
                            return PageBreakType.IMAGE_PAGE_H;
                        } else {
                            return PageBreakType.IMAGE_PAGE_H;
                        }
                    }
                } else {
                    LogAppender.warn(lineNum, "キャプションがあるため画像単ページ化されません");
                }
            } else {
                LogAppender.warn(lineNum, "タグ内のため画像単ページ化できません");
            }
        }
        //単ページ化も回り込みもない
        if (imageWidth > dispW) {
            //横がはみ出している
            if (imageWidth / imageHeight > (double) dispW / dispH)
                return PageBreakType.IMAGE_INLINE_W;
            else
                //縦の方が長い
                return PageBreakType.IMAGE_INLINE_H;
        }
        //縦がはみ出している
        if (imageHeight > dispH)
            return PageBreakType.IMAGE_INLINE_H;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return PageBreakType.IMAGE_PAGE_NONE;
}
Also used : ImageInfo(com.github.hmdev.info.ImageInfo) IOException(java.io.IOException)

Aggregations

ImageInfo (com.github.hmdev.info.ImageInfo)11 IOException (java.io.IOException)7 ZipArchiveEntry (org.apache.commons.compress.archivers.zip.ZipArchiveEntry)5 BufferedInputStream (java.io.BufferedInputStream)4 SectionInfo (com.github.hmdev.info.SectionInfo)3 RarException (com.github.junrar.exception.RarException)3 BufferedWriter (java.io.BufferedWriter)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 FileInputStream (java.io.FileInputStream)3 OutputStreamWriter (java.io.OutputStreamWriter)3 ZipArchiveInputStream (org.apache.commons.compress.archivers.zip.ZipArchiveInputStream)3 ChapterLineInfo (com.github.hmdev.info.ChapterLineInfo)2 Archive (com.github.junrar.Archive)2 FileHeader (com.github.junrar.rarfile.FileHeader)2 InputStream (java.io.InputStream)2 ArchiveEntry (org.apache.commons.compress.archivers.ArchiveEntry)2 BookInfo (com.github.hmdev.info.BookInfo)1 ChapterInfo (com.github.hmdev.info.ChapterInfo)1 GaijiInfo (com.github.hmdev.info.GaijiInfo)1