I am trying to display all the images available in a blackberry device inside a list. How can I scan and fetch all images names in blackberry using java apis?
Use the following class to locate all the images in the device. At the beginning, you call the function without giving any value to the string: checkImages("");
public void checkImages(String imagePath) {
String path = "";
if (imagePath.equals(""))
path = "file:///SDCard/";
else
path = imagePath;
try {
FileConnection fileConnection = (FileConnection)Connector.open(path);
if (fileConnection.isDirectory()) {
Enumeration directoryEnumerator = fileConnection.list("*", true);
Vector contentVector = new Vector();
while(directoryEnumerator.hasMoreElements()) {
contentVector.addElement(directoryEnumerator.nextElement());
}
fileConnection.close();
for (int i = 0 ; i < contentVector.size() ; i ++) {
String name = (String) contentVector.elementAt(i);
checkImages(path + name);
}
}
else {
if (path.toLowerCase().endsWith(".jpg")) {
imm.addElement(path); // your Vector
fileConnection.close();
}
}
} catch (Exception ex) { }
}
Related
Upon migrating from VS2013 to VS2017 i'm running into an unexpected character issue.
Everything builds fine in msbuild 12.0 and VS2013, but when moving to 15.0 I receive hundreds of:
CS1519 Invalid token '?' in class, struct, or interface member declaration
in msbuild command line.
Building inside VS2017 returns:
CS1056 Unexpected character ''
var businessRuleData = principal.GetBusinessRule(
BusinessRuleEnum.CONTENT_REPOSITORY);
Error occurs at Ch66 which is (B in between that area. The character that is hidden becomes a ? in WordPad. However, as mentioned the same code builds fine in msbuild 12.0. Deletion of all code and re-downloading form TFS didn't solve the issue
Solution Code
Note: Search in code for change_me and make sure to change to whatever your desired items are.
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace FixZeroWidthSpace
{
class Program
{
static void Main(string[] args)
{
// change to your directory
var files = Directory.GetFiles(#"D:\change_me", "*.cs", SearchOption.AllDirectories);
var counter = 0;
var counterEdited = 0;
var totalFiles = files.Length;
var failed = new List<string>();
var found = new List<string>();
TfsTeamProjectCollection tpc = null;
Workspace ws = null;
foreach (var file in files)
{
if(counter % 10 == 0)
{
Console.WriteLine("Searched {0} or {1} files, {2} have been edited.", counter, totalFiles, counterEdited);
}
// change to any folders you want to ignore or remove if none
if (!file.Contains("change_me_ignore_folder_name"))
{
string text = File.ReadAllText(file);
var regex = new Regex("[\u200B-\u200D\uFEFF]");
var newText = regex.Replace(text, "");
if (text != newText)
{
try
{
if (ws == null || tpc == null)
{
// change to your TFS server
tpc = new TfsTeamProjectCollection(new Uri(#"http://change_me_your_tfs_url/tfs/DefaultCollection"));
ws = FindWorkspaceByPath(tpc, file);
}
FileAttributes attributes = File.GetAttributes(file);
if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
{
attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
File.SetAttributes(file, attributes);
}
ws.PendEdit(file);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// Make the file RW
attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
File.SetAttributes(file, attributes);
}
File.WriteAllText(file, newText);
found.Add(file);
counterEdited++;
}
catch(Exception ex)
{
failed.Add(file);
}
}
}
counter++;
}
tpc.Dispose();
File.WriteAllLines(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\found.txt", found);
File.WriteAllLines(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\failed.txt", failed);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
{
return attributes & ~attributesToRemove;
}
private static Workspace FindWorkspaceByPath(TfsTeamProjectCollection tfs, string workspacePath)
{
VersionControlServer versionControl = tfs.GetService<VersionControlServer>();
WorkspaceInfo workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(workspacePath);
if (workspaceInfo != null)
{
return versionControl.GetWorkspace(workspaceInfo);
}
// No Workspace found using method 1, try to query all workspaces the user has on this machine.
Workspace[] workspaces = versionControl.QueryWorkspaces(null, Environment.UserName, Environment.MachineName);
foreach (Workspace w in workspaces)
{
foreach (WorkingFolder f in w.Folders)
{
if (f.LocalItem.Equals(workspacePath))
{
return w;
}
}
}
if (workspaces.Length > 0)
{
return workspaces[0];
}
throw new Exception(String.Format("TFS Workspace cannot be determined for {0}.", workspacePath));
}
}
}
Solution
Remove all invalid characters as MSBuild 15.0 and VS2017 are more strict on these unicode characters.
The following code can be utilized to accomplish the removal of all code in a Folder that is an issue. I utilized this as the changes required were too large to be done by hand.
C# Code
Variables
[Insert Folder to Scan] : Example C:\TFS\Code\Branch\Folder
[Insert Folder To Ignore] : Example 3rdPartyCode
Code
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace FixZeroWidthSpace
{
class Program
{
static void Main(string[] args)
{
var files = Directory.GetFiles(#"D:\TFS\210-219\212\MCET_212", "*.cs", SearchOption.AllDirectories);
var counter = 0;
var counterEdited = 0;
var totalFiles = files.Length;
var failed = new List<string>();
var found = new List<string>();
foreach (var file in files)
{
if(counter % 10 == 0)
{
Console.WriteLine("Searched {0} or {1} files, {2} have been edited.", counter, totalFiles, counterEdited);
}
if (!file.Contains("[Insert Folder To Ignore]"))
{
string text = File.ReadAllText(file);
var regex = new Regex("[\u200B-\u200D\uFEFF]");
var newText = regex.Replace(text, "");
if (text != newText)
{
try
{
FileAttributes attributes = File.GetAttributes(file);
if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
{
attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
File.SetAttributes(file, attributes);
}
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// Make the file RW
attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
File.SetAttributes(file, attributes);
}
File.WriteAllText(file, newText);
found.Add(file);
counterEdited++;
}
catch(Exception ex)
{
failed.Add(file);
}
}
}
counter++;
}
File.WriteAllLines(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\found.txt", found);
File.WriteAllLines(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\failed.txt", failed);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
{
return attributes & ~attributesToRemove;
}
}
}
C# Code w/ TFS Checkout
Variables
[Insert Folder to Scan] : Example C:\TFS\Code\Branch\Folder
[Insert Folder To Ignore] : Example 3rdPartyCode
[Insert URI to TFS Server Collection] : Example http://tfs.company.com:8080/tfs/DefaultCollection
Code
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace FixZeroWidthSpace
{
class Program
{
static void Main(string[] args)
{
var files = Directory.GetFiles(#"[Insert Folder to Scan]", "*.cs", SearchOption.AllDirectories);
var counter = 0;
var counterEdited = 0;
var totalFiles = files.Length;
var failed = new List<string>();
var found = new List<string>();
TfsTeamProjectCollection tpc = null;
Workspace ws = null;
foreach (var file in files)
{
if(counter % 10 == 0)
{
Console.WriteLine("Searched {0} or {1} files, {2} have been edited.", counter, totalFiles, counterEdited);
}
if (!file.Contains("3rdparty"))
{
string text = File.ReadAllText(file);
var regex = new Regex("[\u200B-\u200D\uFEFF]");
var newText = regex.Replace(text, "");
if (text != newText)
{
try
{
if (ws == null || tpc == null)
{
tpc = new TfsTeamProjectCollection(new Uri(#"[Insert URI to TFS Server Collection]"));
ws = FindWorkspaceByPath(tpc, file);
}
FileAttributes attributes = File.GetAttributes(file);
if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
{
attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
File.SetAttributes(file, attributes);
}
ws.PendEdit(file);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// Make the file RW
attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
File.SetAttributes(file, attributes);
}
File.WriteAllText(file, newText);
found.Add(file);
counterEdited++;
}
catch(Exception ex)
{
failed.Add(file);
}
}
}
counter++;
}
tpc.Dispose();
File.WriteAllLines(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\found.txt", found);
File.WriteAllLines(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\failed.txt", failed);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
{
return attributes & ~attributesToRemove;
}
private static Workspace FindWorkspaceByPath(TfsTeamProjectCollection tfs, string workspacePath)
{
VersionControlServer versionControl = tfs.GetService<VersionControlServer>();
WorkspaceInfo workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(workspacePath);
if (workspaceInfo != null)
{
return versionControl.GetWorkspace(workspaceInfo);
}
// No Workspace found using method 1, try to query all workspaces the user has on this machine.
Workspace[] workspaces = versionControl.QueryWorkspaces(null, Environment.UserName, Environment.MachineName);
foreach (Workspace w in workspaces)
{
foreach (WorkingFolder f in w.Folders)
{
if (f.LocalItem.Equals(workspacePath))
{
return w;
}
}
}
throw new Exception(String.Format("TFS Workspace cannot be determined for {0}.", workspacePath));
}
}
}
I recently found this happening in one of my solutions. It is nothing present in my code.
If I do a solution clean (right click on the solution -> Clean Solution) the problem goes away.
I found some examples for how to extract images from PDF using iText. But what I am looking for is to get the images from PDF by coordinates.
Is it possible? If yes then how it can be done.
Along the lines of the iText example ExtractImages you can extract code like this:
PdfReader reader = new PdfReader(resourceStream);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
ImageRenderListener listener = new ImageRenderListener("testpdf");
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
parser.processContent(i, listener);
}
The ImageRenderListener is defined like this:
class ImageRenderListener implements RenderListener
{
final String name;
int counter = 100000;
public ImageRenderListener(String name)
{
this.name = name;
}
public void beginTextBlock() { }
public void renderText(TextRenderInfo renderInfo) { }
public void endTextBlock() { }
public void renderImage(ImageRenderInfo renderInfo)
{
try
{
PdfImageObject image = renderInfo.getImage();
if (image == null) return;
int number = renderInfo.getRef() != null ? renderInfo.getRef().getNumber() : counter++;
String filename = String.format("%s-%s.%s", name, number, image.getFileType());
FileOutputStream os = new FileOutputStream(filename);
os.write(image.getImageAsBytes());
os.flush();
os.close();
PdfDictionary imageDictionary = image.getDictionary();
PRStream maskStream = (PRStream) imageDictionary.getAsStream(PdfName.SMASK);
if (maskStream != null)
{
PdfImageObject maskImage = new PdfImageObject(maskStream);
filename = String.format("%s-%s-mask.%s", name, number, maskImage.getFileType());
os = new FileOutputStream(filename);
os.write(maskImage.getImageAsBytes());
os.flush();
os.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
As you see the ImageRenderListener method renderImage retrieves an argument ImageRenderInfo. This arguments has methods
getStartPoint giving you a vector in User space representing the start point of the xobject and
getImageCTM giving you the coordinate transformation matrix active when this image was rendered. Coordinates are in User space.
The latter gives you the information which exact manipulation on a 1x1 user space unit square are used to actually draw the image. As you are aware, an image may be rotated, stretched, skewed, and moved (the former method actually extracts its result from the matrix from the "moved" information).
What I want to do is simply to upload a photo to a webservice using mono touch/mono droid and mvvmcross, hopefully in a way so I only have to write the code once for both android and IOS :)
My initial idea is to let the user pick an image (in android using an intent) get the path for the image. Then use MvxResourceLoader resourceLoader to open an stream from the path and then use restsharp for creating a post request with the stream.
However I already hit a wall, when the user picks an image the path is e.g. "/external/images/media/13". this path results in a file not found exception when using the MvxResourceLoader resourceLoader.
Any ideas to why I get the exception or is there an better way to achieve my goal?
This is how I ended up doinging it - thank you stuart and to all the links :)
public class PhotoService :IPhotoService, IMvxServiceConsumer<IMvxPictureChooserTask>,IMvxServiceConsumer<IAppSettings>
{
private const int MaxPixelDimension = 300;
private const int DefaultJpegQuality = 64;
public void ChoosePhotoForEventItem(string EventGalleryId, string ItemId)
{
this.GetService<IMvxPictureChooserTask>().ChoosePictureFromLibrary(
MaxPixelDimension,
DefaultJpegQuality,
delegate(Stream stream) { UploadImage(stream,EventGalleryId,ItemId); },
() => { /* cancel is ignored */ });
}
private void UploadImage(Stream stream, string EventGalleryId, string ItemId)
{
var settings = this.GetService<IAppSettings>();
string url = string.Format("{0}/EventGallery/image/{1}/{2}", settings.ServiceUrl, EventGalleryId, ItemId);
var uploadImageController = new UploadImageController(url);
uploadImageController.OnPhotoAvailableFromWebservice +=PhotoAvailableFromWebservice;
uploadImageController.UploadImage(stream,ItemId);
}
}
public class PhotoStreamEventArgs : EventArgs
{
public Stream PictureStream { get; set; }
public Action<string> OnSucessGettingPhotoFileName { get; set; }
public string URL { get; set; }
}
public class UploadImageController : BaseController, IMvxServiceConsumer<IMvxResourceLoader>, IMvxServiceConsumer<IErrorReporter>, IMvxServiceConsumer<IMvxSimpleFileStoreService>
{
public UploadImageController(string uri)
: base(uri)
{
}
public event EventHandler<PhotoStreamEventArgs> OnPhotoAvailableFromWebservice;
public void UploadImage(Stream stream, string name)
{
UploadImageStream(stream, name);
}
private void UploadImageStream(Stream obj, string name)
{
var request = new RestRequest(base.Uri, Method.POST);
request.AddFile("photo", ReadToEnd(obj), name + ".jpg", "image/pjpeg");
//calling server with restClient
var restClient = new RestClient();
try
{
this.ReportError("Billedet overføres", ErrorEventType.Warning);
restClient.ExecuteAsync(request, (response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
//upload successfull
this.ReportError("Billedet blev overført", ErrorEventType.Warning);
if (OnPhotoAvailableFromWebservice != null)
{
this.OnPhotoAvailableFromWebservice(this, new PhotoStreamEventArgs() { URL = base.Uri });
}
}
else
{
//error ocured during upload
this.ReportError("Billedet kunne ikke overføres \n" + response.StatusDescription, ErrorEventType.Warning);
}
});
}
catch (Exception e)
{
this.ReportError("Upload completed succesfully...", ErrorEventType.Warning);
if (OnPhotoAvailableFromWebservice != null)
{
this.OnPhotoAvailableFromWebservice(this, new PhotoStreamEventArgs() { URL = url });
}
}
}
//method for converting stream to byte[]
public byte[] ReadToEnd(System.IO.Stream stream)
{
long originalPosition = stream.Position;
stream.Position = 0;
try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
stream.Position = originalPosition;
}
}
}
Try:
Issues taking images and showing them with MvvmCross on WP
Need an example of take a Picture with MonoDroid and MVVMCross
https://github.com/Redth/WshLst/ - uses Xam.Mobile for it's picture taking
After taking a picture in my app I want to get the image (by it's path).
I see lots of examples on how to get an image, the only problem is that it no longer is possible doing it by using Connector.open() since Connector is deprecated now.
What to use instead?
conn = (FileConnection)Connector.open("file:///SDCard/BlackBerry/pictures/" + picture);
try {
InputStream input = null;
input = fconn.openInputStream();
int available = 0;
available = input.available();
int fSz = (int)fconn.fileSize();
byte[] data = new byte[fSz];
input.read(data, 0, fSz);
image = EncodedImage.createEncodedImage(data,0,data.length);
bkBitmap = image.getBitmap();
} catch(ControlledAccessException e) {
pLog = "*** Problem Accessing image file:" + e;
EventLogger.logEvent( GUID, pLog.getBytes() );
}
Thanks!
Try this code:
public class LoadingScreen extends MainScreen
{
public LoadingScreen()
{
setTitle("Loading Screen");
createGUI();
}
private void createGUI()
{
BitmapField bitmapField=new BitmapField(getTheImage());
add(bitmapField);
}
private Bitmap getTheImage()
{
Bitmap bitmap=null,scaleBitmap=null;
InputStream inputStream=null;
FileConnection fileConnection=null;
try
{
fileConnection=(FileConnection) Connector.open("file:///SDCard/BlackBerry/pictures/"+"background.png");
if(fileConnection.exists())
{
inputStream=fileConnection.openInputStream();
byte[] data=new byte[(int)fileConnection.fileSize()];
data=IOUtilities.streamToBytes(inputStream);
inputStream.close();
fileConnection.close();
bitmap=Bitmap.createBitmapFromBytes(data,0,data.length,1);
//You can return this bitmap otherwise, after this you can scale it according to your requirement; like...
scaleBitmap=new Bitmap(150, 150);
bitmap.scaleInto(scaleBitmap, Bitmap.FILTER_LANCZOS);
}
else
{
scaleBitmap=Bitmap.getBitmapResource("noimage.png");//Otherwise, Give a Dialog here;
}
}
catch (Exception e)
{
try
{
if(inputStream!=null)
{
inputStream.close();
}
if(fileConnection!=null)
{
fileConnection.close();
}
}
catch (Exception exp)
{
}
scaleBitmap=Bitmap.getBitmapResource("noimage.png");//Your known Image;
}
return scaleBitmap;//return the scale Bitmap not the original bitmap;
}
}
I got like this below Image:
I am successfully able to extract images from a pdf using pdfsharp. The image are of CCITFFaxDecode. But in the tiff image created , the image is getting rotated. Any idea what might be going wrong?
This is the code im using :
byte[] data = xObject.Stream.Value;
Tiff tiff = BitMiracle.LibTiff.Classic.Tiff.Open("D:\\clip_TIFF.tif", "w");
tiff.SetField(TiffTag.IMAGEWIDTH, (uint)(width));
tiff.SetField(TiffTag.IMAGELENGTH, (uint)(height));
tiff.SetField(TiffTag.COMPRESSION, (uint)BitMiracle.LibTiff.Classic.Compression.CCITTFAX4);
tiff.SetField(TiffTag.BITSPERSAMPLE, (uint)(bpp));
tiff.WriteRawStrip(0,data,data.Length);
tiff.Close();
Since the question is still tagged w/iTextSharp might as add some code, even though it doesn't look like you're using the library here. PDF parsing support was added starting in iText[Sharp] 5.
Didn't have an test PDF with the image type you're using, but found one here (see the attachment). Here's a very simple working example in ASP.NET (HTTP handler .ashx) using that test PDF document to get you going:
<%# WebHandler Language="C#" Class="CCITTFaxDecodeExtract" %>
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using Dotnet = System.Drawing.Image;
using System.Drawing.Imaging;
public class CCITTFaxDecodeExtract : IHttpHandler {
public void ProcessRequest (HttpContext context) {
HttpServerUtility Server = context.Server;
HttpResponse Response = context.Response;
string file = Server.MapPath("~/app_data/CCITTFaxDecode.pdf");
PdfReader reader = new PdfReader(file);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
MyImageRenderListener listener = new MyImageRenderListener();
for (int i = 1; i <= reader.NumberOfPages; i++) {
parser.ProcessContent(i, listener);
}
for (int i = 0; i < listener.Images.Count; ++i) {
string path = Server.MapPath("~/app_data/" + listener.ImageNames[i]);
using (FileStream fs = new FileStream(
path, FileMode.Create, FileAccess.Write
))
{
fs.Write(listener.Images[i], 0, listener.Images[i].Length);
}
}
}
public bool IsReusable { get { return false; } }
/*
* see: TextRenderInfo & RenderListener classes here:
* http://api.itextpdf.com/itext/
*
* and Google "itextsharp extract images"
*/
public class MyImageRenderListener : IRenderListener {
public void RenderText(TextRenderInfo renderInfo) { }
public void BeginTextBlock() { }
public void EndTextBlock() { }
public List<byte[]> Images = new List<byte[]>();
public List<string> ImageNames = new List<string>();
public void RenderImage(ImageRenderInfo renderInfo) {
PdfImageObject image = renderInfo.GetImage();
PdfName filter = image.Get(PdfName.FILTER) as PdfName;
if (filter == null) {
PdfArray pa = (PdfArray) image.Get(PdfName.FILTER);
for (int i = 0; i < pa.Size; ++i) {
filter = (PdfName) pa[i];
}
}
if (PdfName.CCITTFAXDECODE.Equals(filter)) {
using (Dotnet dotnetImg = image.GetDrawingImage()) {
if (dotnetImg != null) {
ImageNames.Add(string.Format(
"{0}.tiff", renderInfo.GetRef().Number)
);
using (MemoryStream ms = new MemoryStream()) {
dotnetImg.Save(
ms, ImageFormat.Tiff);
Images.Add(ms.ToArray());
}
}
}
}
}
}
}
If the image(s) is/are being rotated, see this thread on the iText mailing list; perhaps some of the pages in the PDF document have been rotated.
By the by this is the complete code which is extracting the image from the pdf, but rotating it. Sorry about the length of the code.
PdfDocument document = PdfReader.Open("D:\\Sample.pdf");
PdfDictionary resources =document.pages.Elements.GetDictionary("/Resources");
PdfDictionary xObjects = resources.Elements.GetDictionary("/XObject");
if (xObjects != null)
{
ICollection<PdfItem> items = xObjects.Elements.Values;
// Iterate references to external objects
foreach (PdfItem item in items)
{
PdfReference reference = item as PdfReference;
if (reference != null)
{
PdfDictionary xObject = reference.Value as PdfDictionary;
// Is external object an image?
if (xObject != null && xObject.Elements.GetString("/Subtype") == "/Image")
{
string filter = xObject.Elements.GetName("/Filter");
if (filter.Equals("/CCITTFaxDecode"))
{
int width = xObject.Elements.GetInteger(PdfImage.Keys.Width);
int height = xObject.Elements.GetInteger(PdfImage.Keys.Height);
int bpp = xObject.Elements.GetInteger(PdfImage.Keys.BitsPerComponent);
byte[] data = xObject.Stream.Value;
Tiff tiff = BitMiracle.LibTiff.Classic.Tiff.Open("D:\\sample.tif", "w");
tiff.SetField(TiffTag.IMAGEWIDTH, (uint)(width));
tiff.SetField(TiffTag.IMAGELENGTH, (uint)(height));
tiff.SetField(TiffTag.COMPRESSION, (uint)BitMiracle.LibTiff.Classic.Compression.CCITTFAX4);
tiff.SetField(TiffTag.BITSPERSAMPLE, (uint)(bpp));
tiff.SetField(TiffTag.STRIPOFFSETS, 187);
tiff.WriteRawStrip(0,data,data.Length);
tiff.Close();
}
}
}
}
}