Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9743

(C#) PDFを読み込んで、埋め込まれた画像をJPGファイルとして書き出す(DCTDecodeのStream内をママ書き出しているだけなのでかなり雑)

$
0
0
(C#) PDFを読み込んで、埋め込まれた画像をJPGファイルとして書き出す (DCTDecodeのStream内をママ書き出しているだけなのでかなり雑) ・前回 の応用です ・C#単体で、PDFをバイト列に読み込んで、処理しています ・objの中に、DCTDecodeと記載ある時のみ、streamの中身を.jpgという名で、書き出しているだけです。 ・画像形式などを一切判定していないので、書き出されたものが画像として読めない場合も往々にしてありますが、割り切ればそこそこ有用です。 pdf_jpg_out1.cs //c:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe pdf_jpg_out1.cs using System; using System.IO; class pdf_jpg_out1 { //*1 static void Main(string[] args) { //*2 string p_fn = @"" + args[0]; byte[] data = File.ReadAllBytes(p_fn); int ImgCnt = 1; int ARCN = 5; //array_count string[] st = new string[ARCN]; st[0] = "/DCTDecode"; st[1] = " obj"; st[2] = "endobj"; st[3] = ">stream"; st[4] = "endstream"; byte[][] d = new byte[ARCN][]; for(int i=0; i<ARCN; ++i) d[i] = System.Text.Encoding.ASCII.GetBytes(st[i]); byte[][] dm = new byte[ARCN][]; for(int i=0; i<ARCN; ++i) dm[i] = new byte[d[i].Length]; int stream_stt = 0; int stream_size = 0; bool outFlg = false; for(int i=0;i<data.Length-st[0].Length;i++){ for(int j=0; j<ARCN; ++j) Array.Copy(data,i,dm[j],0,d[j].Length); bool[] aEq = new bool[ARCN]; for(int j=0; j<ARCN; ++j){ aEq[j] = System.Linq.Enumerable.SequenceEqual(d[j], dm[j]); if(aEq[j]){ //" obj" if(j==1){ outFlg = false; //リセット } //"/DCTDecode" if(j==0){ outFlg = true; } //">stream" if(j==3){ stream_stt = (int)(i+(int)d[j].Length+2); } //"endstream" if(j==4){ stream_size = (int)((int)i-3) - stream_stt +1; if(outFlg){ byte[] data_out = new byte[stream_size]; Array.Copy(data,stream_stt,data_out,0,stream_size); File.WriteAllBytes("_Jpg_out" +ImgCnt+ ".jpg", data_out); Console.WriteLine("_Jpg_out" +ImgCnt+ ".jpg"); ImgCnt++; } } string tx = System.Text.Encoding.ASCII.GetString(dm[j]); //Console.WriteLine(i + "_" + tx); } } } } //*2 } //*1 実行例 対象例 ためしにこのPDFでやってみると (総務省のサイトより) https://www.soumu.go.jp/main_content/000542668.pdf 1)PDFでの表示 2)抜き出したJPG 参考 (C#) PDFを読み込んで、Stream内をすべて別ファイルに書き出す、サンプルソース https://qiita.com/santarou6/items/5272458b1e9ff2058327 C# JpgからPDFへ変換(1Jpgファイルを1ページとしたPDFファイルの作成) https://qiita.com/santarou6/items/ff24500c13d05b12a940 iTextSharp きっちりやりたい方は、以下DLLなどを使ってください https://itextpdf.com/en/products/itext-7 https://github.com/itext/itext7-dotnet iText 7 Community for .NET (former iTextSharp) consists of several dlls. C#でPDFファイルから画像を抜き出す 導入編 (iTextSharp) https://araramistudio.jimdo.com/2021/03/19/c-%E3%81%A7pdf%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%8B%E3%82%89%E7%94%BB%E5%83%8F%E3%82%92%E6%8A%9C%E3%81%8D%E5%87%BA%E3%81%99-itextsharp/

Viewing all articles
Browse latest Browse all 9743

Trending Articles