I found this code on StackOverflow. & This code works great for converting a website to image. However, instead of navigating to a new URL, can this code be modified to capture the current website?
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;
public class WebsiteToImage
{
private Bitmap m_Bitmap;
private string m_Url;
private string m_FileName = string.Empty;
public WebsiteToImage(string url)
{
// Without file
m_Url = url;
}
public WebsiteToImage(string url, string fileName)
{
// With file
m_Url = url;
m_FileName = fileName;
}
public Bitmap Generate()
{
// Thread
var m_thread = new Thread(_Generate);
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
return m_Bitmap;
}
private void _Generate()
{
var browser = new WebBrowser { ScrollBarsEnabled = false };
browser.Navigate(m_Url);
browser.DocumentCompleted += WebBrowser_DocumentCompleted;
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
browser.Dispose();
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Capture
var browser = (WebBrowser)sender;
browser.ClientSize = new Size(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom);
browser.ScrollBarsEnabled = false;
m_Bitmap = new Bitmap(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom);
browser.BringToFront();
browser.DrawToBitmap(m_Bitmap, browser.Bounds);
// Save as file?
if (m_FileName.Length > 0)
{
// Save
m_Bitmap.SaveJPG100(m_FileName);
}
}
}
public static class BitmapExtensions
{
public static void SaveJPG100(this Bitmap bmp, string filename)
{
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bmp.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}
public static void SaveJPG100(this Bitmap bmp, Stream stream)
{
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bmp.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}
public static ImageCodecInfo GetEncoder(ImageFormat format)
{
var codecs = ImageCodecInfo.GetImageDecoders();
foreach (var codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
// Return
return null;
}
}
Related
I've some hard time trying to display images in my UWP App.
My images are located in the Images library.
The question is:
How to show jpg in the Image Xaml control on a UWP, that is not in the projects "Assets"?
So far using Binding, I’ve
Try to set Image.Source to the full path with no success, image control remains blank. (for file access retriction a guess)
Try using setting BitMapImage to the Image.Source property with no success, image control remains blank. (for file access retriction a guess)
Try to assign FileStorage class to the Image.Source property with no success, image control remains blank.
Try to load the image file in a stream and load the stream in the BitmapImage, but there I’ve threading issues. More about this below.
About the threading issue, I’ve come to two issues for now.
When loading the file/stream:
var file = File.ReadAllBytes(_currentImagePath);
I get
System.InvalidOperationException: 'Synchronous operations should not be performed on the UI thread. Consider wrapping this method in Task.Run.'
When using Task.Run on any manner I get an exception when trying to set the Bitmap source
The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
var bitmap = new BitmapImage();
return await Task.Run(async () =>
{
var file = File.ReadAllBytes(_currentImagePath);
using (var stream = new InMemoryRandomAccessStream())
{
await stream.WriteAsync(file.AsBuffer());
stream.Seek(0);
await bitmap.SetSourceAsync(stream); // **Exception here**
return bitmap;
}
});
Here the full source code:
namespace App1.Images
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Imaging;
using App1.Annotations;
public class ImagesLibrairies : INotifyPropertyChanged
{
private readonly HashSet<Image> _images;
private readonly string _fileTypes;
private readonly HashSet<Image> _preferrednessFiles;
private readonly DispatcherTimer _timer;
private ulong _minFileSize = 5 * 1024; // 5k in bytes
private ulong _maxFileSize = 1024 * 1024 * 20; //20 MBytes
private int _imageIndex = 0;
public ImagesLibrairies()
{
_preferrednessFiles = new HashSet<Image>();
_fileTypes = "*.jpg;*.jpeg;*.bmp;*.tif"; // ignore *.ico;*.png;*.svg;*.gif
_images = new HashSet<Image>();
_timer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, 5) };
_timer.Tick += _timer_Tick;
}
private Uri _currentImage;
public Uri CurrentImage
{
get => _currentImage;
private set
{
_currentImage = value;
OnPropertyChanged(nameof(CurrentImage));
OnPropertyChanged(nameof(Image));
}
}
public async Task<BitmapImage> GetBitmapImage()
{
var bitmap = new BitmapImage();
return await Task.Run(async () =>
{
var file = File.ReadAllBytes(_currentImagePath);
using (var stream = new InMemoryRandomAccessStream())
{
await stream.WriteAsync(file.AsBuffer());
stream.Seek(0);
await bitmap.SetSourceAsync(stream);
return bitmap;
}
});
}
public BitmapImage Image
{
get
{
if (!string.IsNullOrEmpty(_currentImagePath))
return GetBitmapImage().Result;
return null;
}
}
private string _currentImagePath;
public string CurrentImagePath
{
get => _currentImagePath;
set
{
_currentImagePath = value;
OnPropertyChanged(nameof(CurrentImagePath));
CurrentImage = new Uri(value);
}
}
public object CurrentStorageFile { get; set; }
private void _timer_Tick(object sender, object e)
{
SetNext();
}
public async Task ScanLibrairies()
{
var picturesFolder = KnownFolders.PicturesLibrary;
var files = await picturesFolder.GetFilesAsync();
foreach (var file in files)
{
Debug.WriteLine(file.Name + ", " + file.DateCreated);
if (_images.Count >= int.MaxValue)
return;
var prop = await file.GetBasicPropertiesAsync();
var imageLocation = new Image
{
StorageFile = file,
Properties = prop
};
if (imageLocation.Properties.Size < _minFileSize || imageLocation.Properties.Size > _maxFileSize)
continue;
if (_preferrednessFiles.Any(o => o.Equals(imageLocation) && o.Preferredness == Preferredness.No))
continue;
_images.Add(imageLocation);
}
}
public void SetNext()
{
if (_images == null || !_images.Any())
{
return;
}
_imageIndex++;
var image = _images.Skip(_imageIndex).FirstOrDefault();
if (image != null)
{
Debug.WriteLine($"Displaying: {image.StorageFile.Path}");
}
CurrentImagePath = image?.StorageFile.Path;
CurrentImage = new Uri(CurrentImagePath);
}
public void SetPrevious()
{
if (_images == null || !_images.Any())
return;
_imageIndex--;
var image = _images.Skip(_imageIndex).FirstOrDefault();
CurrentImagePath = image?.StorageFile.Path;
}
public void LikeThisPicture(Image picture)
{
var pic = _preferrednessFiles.FirstOrDefault(o => o.Equals(picture));
if (pic == null)
{
picture.Preferredness = Preferredness.Very;
_preferrednessFiles.Add(picture);
return;
}
pic.Preferredness = Preferredness.Very;
}
public void DislikeThisPicture(Image picture)
{
var pic = _preferrednessFiles.FirstOrDefault(o => o.Equals(picture));
if (pic == null)
{
picture.Preferredness = Preferredness.No;
_preferrednessFiles.Add(picture);
return;
}
pic.Preferredness = Preferredness.No;
}
public void StartAsync()
{
ScanLibrairies();
_timer.Start();
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Here the xaml markup
<Page.DataContext>
<images:ImagesLibrairies/>
</Page.DataContext>
<Grid >
<!--Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">-->
<Image Stretch="UniformToFill" Margin="15">
<Image.Source>
<BitmapImage UriSource="{Binding Image}"></BitmapImage>
<!--<BitmapImage UriSource="{Binding CurrentImagePath}"></BitmapImage>-->
<!--<BitmapImage UriSource="D:\Utilisateurs\hugod\OneDrive\Images\jouets\20180106_132041.jpg"></BitmapImage>-->
<!--<BitmapImage UriSource="Assets/Black-And-White-Wall-Brick-Texture-Shadow-WallpapersByte-com-3840x2160.jpg"></BitmapImage>-->
<!--<BitmapImage UriSource="{Binding CurrentStorageFile}"></BitmapImage>-->
</Image.Source>
</Image>
</Grid>
Raymond is right!
CurrentImage = new BitmapImage();
await CurrentImage.SetSourceAsync(await image.StorageFile.OpenAsync(FileAccessMode.Read));
A goody for Raymond!
Attaching the source code for application i have created, its a simple application with collection view and button to choose image from gallery or camera. ios app crashes after taking 8 images continuously from camera.
using CoreGraphics;
using Foundation;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using UIKit;
namespace App2.iOS
{
public class imagesDisplay
{
public bool PlusImg;
public bool uploaded;
public string path { get; set; }
public int id { get; set; }
public imagesDisplay(bool uploaded, bool PlusImg = false, string path = null, int id = 0)
{
this.uploaded = uploaded;
this.PlusImg = PlusImg;
this.path = path;
this.id = id;
}
}
public partial class ViewController : UIViewController
{
public List<imagesDisplay> images = new List<imagesDisplay>();
private UIAlertController alert;
private UIImagePickerController imagePicker;
private NSData imgData;
private NSData thumdata;
public ViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
imgCollection.SetCollectionViewLayout(new LineLayout(), false);
imgCollection.AllowsMultipleSelection = true;
imgCollection.RegisterNibForCell(UINib.FromName("imageceCollectionViewCell", null), imageceCollectionViewCell.Key);
alert = UIAlertController.Create("", "Select image from : ", UIAlertControllerStyle.ActionSheet);
var cameraaction = UIAlertAction.Create("Bruk kamera", UIAlertActionStyle.Default, a =>
{
imagePicker = new UIImagePickerController();
imagePicker.SourceType = UIImagePickerControllerSourceType.Camera;
imagePicker.FinishedPickingMedia += Handle_FinishedPickingMedia;
imagePicker.Canceled += Handle_Canceled;
imagePicker.AllowsImageEditing = false;
this.NavigationController.PresentViewController(imagePicker, true, null);
});
alert.AddAction(cameraaction);
var galleryaction = UIAlertAction.Create("Last opp bilder", UIAlertActionStyle.Default, a =>
{
imagePicker = new UIImagePickerController();
imagePicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary;
imagePicker.FinishedPickingMedia += Handle_FinishedPickingMedia;
imagePicker.Canceled += Handle_Canceled;
imagePicker.AllowsImageEditing = false;
this.NavigationController.PresentViewController(imagePicker, true, null);
});
alert.AddAction(galleryaction);
alert.AddAction(UIAlertAction.Create("Avbryt", UIAlertActionStyle.Cancel, a => { }));
imgCollection.Source = new ImageCollectionSource(images,new WeakReference<UINavigationController>(this.NavigationController));
}
public override void DidReceiveMemoryWarning ()
{
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
partial void UIButton125_TouchUpInside(UIButton sender)
{
this.PresentViewController(alert, true, null);
}
private void Handle_Canceled(object sender, EventArgs e)
{
imagePicker.DismissModalViewController(true);
}
private void Handle_FinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs e)
{
try
{
NSUrl referenceURL = e.Info[new NSString("UIImagePickerControllerReferenceUrl")] as NSUrl;
if (referenceURL != null)
Console.WriteLine("Url:" + referenceURL.ToString());
UIImage originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage;
if (originalImage != null)
{
var documentsDirectory = Environment.GetFolderPath
(Environment.SpecialFolder.Personal);
string timestamp = DateTime.Now.ToString("yyyyMMddHHmmssffff");
string jpgFilename = System.IO.Path.Combine(documentsDirectory, timestamp + ".jpg"); // hardcoded filename, overwritten each time
string thumname = System.IO.Path.Combine(documentsDirectory, timestamp + "_thumb" + ".jpg");
imgData = originalImage.AsJPEG();
Console.WriteLine("Original image size = " + imgData.Length);
thumdata = originalImage.AsJPEG(0.0f);
Console.WriteLine("after funtion compresion image size = " + thumdata.Length);
NSError err = null;
if (imgData.Save(jpgFilename, false, out err))
{
Console.WriteLine("saved as " + jpgFilename);
NSError err1 = null;
if (thumdata.Save(thumname, false, out err1))
{
Console.WriteLine("saved as " + jpgFilename);
}
else
{
Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
}
}
else
{
Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
}
images.Add(new imagesDisplay(false, false, thumname, 0));
}
imgCollection.ReloadData();
imagePicker.DismissViewController(true, null);
}
catch (Exception ex)
{
}
}
}
public class LineLayout : UICollectionViewFlowLayout
{
public LineLayout()
{
ItemSize = new CGSize((UIScreen.MainScreen.Bounds.Width / 2) - 12, (UIScreen.MainScreen.Bounds.Height / 3) - 40);
MinimumInteritemSpacing = 0f;
}
}
}
Force to release the image data before creating the new one:
if (imgData != null) {
imgData.Dispose();
imgData = null;
}
imgData = originalImage.AsJPEG();
Or use local variable with using sentence:
using (NSData imgData = originalImage.AsJPEG()) { //imgData will be disposed immediately at the end of block
//......
}
I've got a normal picturebox in a form, I have an image of a signature that I recover from the database, when I save the image with the signature it had a white background and the signature was black, but when I recover the image it has a black background and the signature is white.
Can anyone explain why this happens and how can I fix it??
You can find the image at the following direction
http://www.mediafire.com/?c91awvyrya98m2c
It is contained in a rar file: Signature.jpg
The code is the following:
using System.Drawing;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
namespace WindowsFormsApplication3
{
class TestForm : System.Windows.Forms.Form
{
PictureBox oPictureBoxSignature;
public Database Db;
public TestForm()
{
Db = DatabaseFactory.CreateDatabase("DBTest");
oPictureBoxSignature = new PictureBox();
}
public bool Save_Record()
{
byte[] Signature = imageToByteArray(oPictureBoxSignature.Image);
return Save(Signature);
}
public bool Save(byte[] Signature)
{
using (DbCommand dbCmd = Db.GetStoredProcCommand("Save_Signature"))
{
Db.AddInParameter(dbCmd, "Signature", DbType.Binary, Signature);
return Db.ExecuteNonQuery(dbCmd) > 0;
}
}
public void Recover_Record(byte[] Signature)
{
oPictureBoxSignature.Image = byteArrayToImage(Signature);
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
if (byteArrayIn != null)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
else
return null;
}
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
if (imageIn != null)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
else
return null;
}
}
}
I want to make an application which captures images using the camera and stores it in the isolated storage of the phone.How ever, i am able to store 7 images in each run(i.e. each time the emulator is activated) and for the eight image that i capture and save, i get an out of memory exception.If I have to store more images in the isolated storage, i have to stop debugging and restart debugging.I am new to wp7 development.I am using the emulator for debugging.Please help
Stream doc_photo;
List<document> doc_list = new List<document>();
document newDoc = new document();
public Page2()
{
InitializeComponent();
}
private void captureDocumentImage(object sender, RoutedEventArgs e)
{
ShowCameraCaptureTask();
}
private void ShowCameraCaptureTask()
{
CameraCaptureTask photoCameraCapture = new CameraCaptureTask();
photoCameraCapture = new CameraCaptureTask();
photoCameraCapture.Completed += new EventHandler<PhotoResult>photoCameraCapture_Completed);
photoCameraCapture.Show();
}
void photoCameraCapture_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
capturedImage.Source = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
doc_photo = e.ChosenPhoto;
}
}
private void SaveToIsolatedStorage(Stream imageStream, string fileName)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(fileName))
{
myIsolatedStorage.DeleteFile(fileName);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(fileName);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(imageStream);
try
{
WriteableBitmap wb = new WriteableBitmap(bitmap);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
catch (OutOfMemoryException e1)
{
MessageBox.Show("memory exceeded");
}
}
}
private void save_buttonclicked(object sender, RoutedEventArgs e)
{
if (namebox.Text != "" && doc_photo!=null)
{
newDoc.doc_name = namebox.Text;
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if(!myIsolatedStorage.DirectoryExists(App.current_panorama_page))
{
myIsolatedStorage.CreateDirectory(App.current_panorama_page);
}
newDoc.photo = App.current_panorama_page + "/" + namebox.Text + ".jpg";//
SaveToIsolatedStorage(doc_photo, newDoc.photo);
doc_list.Add(newDoc);
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
else
{
if (namebox.Text == "")
{
MessageBox.Show("Enter the name");
}
else if (doc_photo == null)
{
MessageBox.Show("Capture an Image");
}
}
}
you are saving the bitmap to 'doc_list', not just the URL, so the phone will have each image you capture in memory. You should probably go for a solution where the images are referenced in the UI using regular image controls and the 'isostore://' URLs.
EDIT:
In the example below I use an ObservableCollection for storing IsoImageWrappers. The latter class handles the connection to isolated storage, by instantiating an isolated file stream with the URI given in constructor.
The ObservableCollection will notify the WP7 framework when new images are added. Storing images is almost as your original proposal.
The list box binding is:
<ListBox Grid.Row="0" Height="495" Margin="0" Name="listBox1" Width="460" >
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding Source}" Width="Auto" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
and the code with ugly inline of helper classes etc:
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
namespace WP7Photo
{
public partial class MainPage : PhoneApplicationPage
{
public class IsoImageWrapper
{
public string Uri { get; set; }
public ImageSource Source
{
get
{
IsolatedStorageFile isostore = IsolatedStorageFile.GetUserStoreForApplication();
var bmi = new BitmapImage();
bmi.SetSource(isostore.OpenFile(Uri, FileMode.Open, FileAccess.Read));
return bmi;
}
}
}
public ObservableCollection<IsoImageWrapper> Images { get; set; }
// Constructor
public MainPage()
{
InitializeComponent();
Images = new ObservableCollection<IsoImageWrapper>();
listBox1.ItemsSource = Images;
}
private void Button1Click(object sender, RoutedEventArgs e)
{
var cameraTask = new CameraCaptureTask();
cameraTask.Completed += new EventHandler<PhotoResult>(cameraTask_Completed);
cameraTask.Show();
}
void cameraTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult != TaskResult.OK)
{
return;
}
StorePhoto(e);
}
private void StorePhoto(PhotoResult photo)
{
IsolatedStorageFile isostore = IsolatedStorageFile.GetUserStoreForApplication();
if (!isostore.DirectoryExists("photos"))
{
isostore.CreateDirectory("photos");
}
var filename = "photos/" + System.IO.Path.GetFileName(photo.OriginalFileName);
if (isostore.FileExists(filename)) { isostore.DeleteFile(filename);}
using (var isoStream = isostore.CreateFile(filename))
{
photo.ChosenPhoto.CopyTo(isoStream);
}
Images.Add(new IsoImageWrapper {Uri = filename});
}
}
}
When I run the code below I get this error
NullreferenceException was unhandled..
below is my code
private void showScannerDialog()
{
this.scanner = null;
this.imageItem = null;
this.getScanner();
WIA.CommonDialog dialog = new WIA.CommonDialog();
Items imageItems = dialog.ShowSelectItems(this.scanner, WiaImageIntent.TextIntent, WiaImageBias.MinimizeSize, false, true, false);
if (imageItems != null)
{
foreach (Item item in imageItems)
{
imageItem = item;
break;
}
}
}
thanks
// complete code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string scannerName;
private Device scanner;
private Item imageItem;
private const int ADF = 1;
private const int FLATBED = 2;
private const int DEVICE_NAME_PROPERTY_ID = 7;
private const int DOCUMENT_HANDLING_PROPERTY_ID = 3088;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
showScannerDialog();
}
public static string[] GetScannerList()
{
ArrayList scannerList = new ArrayList();
DeviceManager deviceManager = new DeviceManager();
if (deviceManager.DeviceInfos.Count == 0)
{
return new string[0]; // return an empty string array
}
foreach (DeviceInfo deviceInfo in deviceManager.DeviceInfos)
{
if (deviceInfo.Type == WiaDeviceType.ScannerDeviceType)
{
Device device = deviceInfo.Connect();
scannerList.Add(getDeviceProperty(device, DEVICE_NAME_PROPERTY_ID));
}
}
return (string[])scannerList.ToArray(typeof(string));
}
public int Init(string scannerName)
{
this.scannerName = scannerName;
this.showScannerDialog();
if (this.imageItem == null)
{
return 0;
}
else
{
return 1;
}
}
public int Scan(string filePath)
{
Tiff tiff = new Tiff(filePath);
bool adf = false;
int numScans = 0;
ArrayList tempFiles = new ArrayList();
// determine if the scanner is set to use an ADF
string docHandlingSelect = getDeviceProperty(this.scanner, DOCUMENT_HANDLING_PROPERTY_ID);
if (docHandlingSelect != "")
{
try
{
if ((int.Parse(docHandlingSelect) & ADF) == ADF)
{
adf = true;
}
}
catch { }
}
while (true)
{
string tempFile = Path.GetTempFileName();
tempFiles.Add(tempFile);
File.Delete(tempFile);
ImageFile wiaFile = (ImageFile)imageItem.Transfer(FormatID.wiaFormatTIFF);
wiaFile.SaveFile(tempFile);
Image tempImage = Image.FromFile(tempFile);
tiff.AddImage(tempImage);
tempImage.Dispose();
numScans++;
if (!adf)
{
DialogResult result =
MessageBox.Show("Do you wish to scan another page and save it to the same file?",
"Scanner Message", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
break;
}
this.showScannerDialog();
if (this.imageItem == null)
{
break;
}
}
}
tiff.Close();
foreach (string f in tempFiles.ToArray(typeof(string)))
{
File.Delete(f);
}
Marshal.ReleaseComObject(imageItem);
if (numScans == 0)
{
throw new Exception("Nothing was scanned.");
}
return 1;
}
private void getScanner()
{
DeviceManager deviceManager = new DeviceManager();
foreach (DeviceInfo deviceInfo in deviceManager.DeviceInfos)
{
if (deviceInfo.Type == WiaDeviceType.ScannerDeviceType)
{
Device device = deviceInfo.Connect();
if (this.scannerName == getDeviceProperty(device, DEVICE_NAME_PROPERTY_ID))
{
this.scanner = device;
}
}
}
}
private void showScannerDialog()
{
this.scanner = null;
this.imageItem = null;
this.getScanner();
WIA.CommonDialog dialog = new WIA.CommonDialog();
Items imageItems = dialog.ShowSelectItems(this.scanner, WiaImageIntent.TextIntent, WiaImageBias.MinimizeSize, false, true, false);
if (imageItems != null)
{
foreach (Item item in imageItems)
{
imageItem = item;
break;
}
}
}
private static string getDeviceProperty(Device device, int propteryID)
{
string retVal = "";
foreach (Property prop in device.Properties)
{
if (prop.PropertyID == propteryID)
{
retVal = prop.get_Value().ToString();
break;
}
}
return retVal;
}
}
}
this.scanner is set to null when you pass it to dialog.ShowSelectItems(). The function may be trying to use it without checking if it is null.