WIA Setting up page size does not work - c#

Im trying to make an app that can scan documents using C# and WIA. But I have come across a problem when setting up the page size property. When I run the scanning process my app throws an error:
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in DigiKnjiga.exe
Additional information: Exception from HRESULT: 0x80210067
I have tried this using these properties: PageSize(3097), PageWidth(3098) & PageHeight(3099), HorizontalExtent(6151) & VerticalExtent(6152). But setting any of these values throws the before mentioned exception.
Here is the event that starts the scanning process:
private void scanNew_Click(object sender, EventArgs e)
{
if (Scanner.ChosenDevice > 0)
{
Device = deviceManager.DeviceInfos[Scanner.ChosenDevice].Connect();
switch (Scanner.ColorCode)
{
case 0://color
Device.Items[1].Properties["6146"].set_Value(1);
break;
case 1://grayscale
Device.Items[1].Properties["6146"].set_Value(2);
break;
case 2://black and white
Device.Items[1].Properties["6146"].set_Value(4);
break;
}
//(DPI)
Device.Items[1].Properties["6147"].set_Value(Scanner.DPI);
Device.Items[1].Properties["6148"].set_Value(Scanner.DPI);
//brightness
Device.Items[1].Properties["Brightness"].set_Value(Scanner.Brightness);
//contrast
Device.Items[1].Properties["Contrast"].set_Value(Scanner.Contrast);
switch (Scanner.Format)
{
case 0://A3
Device.Items[1].Properties["3097"].set_Value(10);
//Device.Items[1].Properties["6151"].set_Value(11692);
//Device.Items[1].Properties["6152"].set_Value(16535);
break;
case 1://A4
Device.Items[1].Properties["3097"].set_Value(0);
//Device.Items[1].Properties["6156"].set_Value(1);
//Device.Items[1].Properties["3098"].set_Value(8267);
//Device.Items[1].Properties["3099"].set_Value(11692);
////Device.Items[1].Properties["6151"].set_Value(1165 * 2);
////Device.Items[1].Properties["6152"].set_Value(1653 * 2);
////Device.Items[1].Properties["3097"].set_Value("0");
break;
case 2://A5
Device.Items[1].Properties["3097"].set_Value(11);
//Device.Items[1].Properties["6151"].set_Value(1165);
//Device.Items[1].Properties["6152"].set_Value(1653);
break;
}
switch (Scanner.FileType)
{
case 0://JPEG
image = (WIA.ImageFile)Device.Items[1].Transfer(WIA.FormatID.wiaFormatJPEG);
break;
case 1://PNG
image = (WIA.ImageFile)Device.Items[1].Transfer(WIA.FormatID.wiaFormatPNG);
break;
case 2://BMP
image = (WIA.ImageFile)Device.Items[1].Transfer(WIA.FormatID.wiaFormatBMP);
break;
case 3://TIFF
image = (WIA.ImageFile)Device.Items[1].Transfer(WIA.FormatID.wiaFormatTIFF);
break;
}
byte[] imageBytes = (byte[])image.FileData.get_BinaryData();
MemoryStream ms = new MemoryStream(imageBytes);
Image image2 = Image.FromStream(ms);
Bitmap smaller= new Bitmap(image2 , new Size(prikazZbirke.Width, prikazZbirke.Height));
prikazStrani.Size = new System.Drawing.Size(image2 .Width, image2 .Height);
prikazStrani.Location = new Point(0, 0);
prikazStrani.Image = image2 ;
image2 .Save("test.jpg");
}
}
I wonder if anyone knows the solution to the this problem and I thank you in advance for your answers. And at the same time apologise for any spelling mistakes as I am not english.

cahnge switch case as following, it could work(but be sure this property(3097) is supported in your scaner)
switch (Scanner.Format)
{
case 0://A3
Device.Properties["3097"].set_Value(10);
break;
case 1://A4
Device.Properties["3097"].set_Value(0);
break;
case 2://A5
Device.Properties["3097"].set_Value(11);
break;
}

Related

Speech Recognition Makes a loop

I'm working on a speech recognizer but every time I say a word it puts it in a loop and keeps saying:
hi my name is Jarvis how can I help you?
What should I do?
I've also tried RecognizeAsyncCancel() but it didn't work!
My code is below:
using System;
using System.IO;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Windows.Forms;
namespace Jarvis
{
public partial class Form1 : Form
{
SpeechRecognitionEngine RecEngine = new SpeechRecognitionEngine();
SpeechSynthesizer speech = new SpeechSynthesizer();
public Form1()
{
InitializeComponent();
Choices choices = new Choices();
string[] text = File.ReadAllLines(Environment.CurrentDirectory + "//grammer.txt");
choices.Add(text);
Grammar grammar = new Grammar(new GrammarBuilder(choices));
RecEngine.LoadGrammar(grammar);
RecEngine.SetInputToDefaultAudioDevice();
RecEngine.RecognizeAsync(RecognizeMode.Multiple);
RecEngine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(RecEngine_SpeechRecognized);
speech.SelectVoiceByHints(VoiceGender.Male);
}
private void RecEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string result = e.Result.Text;
if (result == "Hello")
{
result = "";
result = "Hi, my name is Jarvis, how can I help you";
}
if (result == "Hi")
{
result = "";
result = "It is currently " + DateTime.Now.ToLongTimeString();
}
speech.SpeakAsync(result);
lblresult.Text = result;
result = "";
MessageBox.Show("a");
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
For starters, the setup you are using, is creating your problems, due mostly from arrangement of your code. You should also be incorporating a switch case statement in your recEngine Sub. Also, you are using SpeechSynthesizer speech in your declaration and your SpeechSynthesizer should compliment that and be: speech.Speak("Hi, my name is Jarvis, how can I help you") NOT result = "Hi, my name is Jarvis, how can I help you";.
You don't need this either: result = ""; You can still use If Statements within Case Statements if you want. With that said, here is an example from one of my old projects. I am leaving you with a link to the full project of the code. It will get you on the right path: Just scroll down to the Form1.cs at my repository.
https://github.com/DeadReport77/Scarlett-Speech-Recognition-Final-Production/commit/20f4db5d3b75b03d601d39c6fe54e8261c7976f0
I am the creator of Scarlett Witch Speech Recognition surfacing the net on YouTube and other places. This is the YouTube link: https://www.youtube.com/watch?v=39S10FoCbIA
The code will solve all your problems as well (switch case example):
private void RecEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
switch (e.Result.Text)
{
case "scarlett mute volume":
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle,
(IntPtr)APPCOMMAND_VOLUME_MUTE);
break;
case "scarlett volume up":
int repeat = 10;
for (int i = 0; i < repeat; i++)
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle,
(IntPtr)APPCOMMAND_VOLUME_UP);
break;
case "scarlett volume down":
for (int iter = 0; iter < 10; iter++)
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle,
(IntPtr)APPCOMMAND_VOLUME_DOWN);
break;
case "show commands":
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\list.wav").Play();
Process.Start(#"C:\\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\Commands.txt");
break;
case "tell me who you are":
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\info.wav").Play();
break;
case "scarlett open youtube":
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\youtube.wav").Play();
Process.Start("chrome", "Http://www.youtube.com");
break;
case "scarlett movies":
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\movie.wav").Play();
Process.Start("chrome", "http://www.tubitv.com");
break;
case "scarlett open github":
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\github.wav").Play();
Process.Start("chrome", "Http://www.github.com");
break;
case "open wiki":
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\wiki.wav").Play();
Process.Start("http://www.wikipedia.org/");
break;
case "scarlett microsoft office":
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\word.wav").Play();
Process.Start("winword");
break;
case "stop listening":
recEngine.RecognizeAsyncStop();
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\mic.wav").Play();
break;
case "open command":
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\prompt.wav").Play();
System.Diagnostics.Process.Start("cmd");
break;
case "scarlett run system scan":
Scanning f = new Scanning();
f.Show();
break;
case "commit to memory":
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\storing.wav").Play();
break;
case "scarlett close":
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\shuttingdown.wav").Play();
Sleep(TimeSpan.FromSeconds(2));
Application.Exit();
break;
case "scarlett what day is it":
Scarlett.Speak(DateTime.Today.ToString("dd-MM-yyyy"));
break;
case "scarlett out of the way":
if (WindowState == FormWindowState.Normal)
{
WindowState = FormWindowState.Minimized;
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\standby.wav").Play();
}
break;
case "scarlett come back":
if (WindowState == FormWindowState.Minimized)
{
WindowState = FormWindowState.Normal;
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\comeback.wav").Play();
}
break;
case "disparta":
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\closingapp.wav").Play();
SendKeys.Send("%{F4}");
break;
case "scarlett play rammstein":
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\video.wav").Play();
Process.Start("chrome", "https://www.youtube.com/watch?v=3b4szXcRFcs?autoplay=1&mute=1");
break;
case "page up":
SendKeys.Send("{PGUP}");
break;
case "page down":
SendKeys.Send("{PGDN}");
break;
case "new tab":
SendKeys.Send("^{t}");
break;
case "switch tab":
SendKeys.Send("^{TAB}");
break;
case "magnify":
SendKeys.Send("^{+}");
break;
case "less":
SendKeys.Send("^{-}");
break;
case "scarlett notepad":
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\notepad.wav").Play();
Process.Start("notepad");
break;
case "scarlett visual studios":
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\visual.wav").Play();
Process.Start("devenv.exe");
break;
default:
new SoundPlayer(#"C:\Users\Leeraoy.Jenkins\source\repos\Scarlett\Resources\unknown.wav").Play();
break;
}
}

Removing EXIF Does not work when using Different Encoders to Choose Format

Im using the following code to fix the orientation of image taking into account the EXIF Orientation Tag
static void FixImageOrientation(Image srce)
{
const int ExifOrientationId = 0x112;
// Read orientation tag
if (!srce.PropertyIdList.Contains(ExifOrientationId)) return;
var prop = srce.GetPropertyItem(ExifOrientationId);
var orient = BitConverter.ToInt16(prop.Value, 0);
// Force value to 1
prop.Value = BitConverter.GetBytes((short)1);
srce.SetPropertyItem(prop);
// Rotate/flip image according to <orient>
switch (orient)
{
case 1:
srce.RotateFlip(RotateFlipType.RotateNoneFlipNone);
break;
case 2:
srce.RotateFlip(RotateFlipType.RotateNoneFlipX);
break;
case 3:
srce.RotateFlip(RotateFlipType.Rotate180FlipNone);
break;
case 4:
srce.RotateFlip( RotateFlipType.Rotate180FlipX);
break;
case 5:
srce.RotateFlip(RotateFlipType.Rotate90FlipX);
break;
case 6:
srce.RotateFlip(RotateFlipType.Rotate90FlipNone);
break;
case 7:
srce.RotateFlip(RotateFlipType.Rotate270FlipX);
break;
case 8:
srce.RotateFlip(RotateFlipType.Rotate270FlipNone);
break;
default:
srce.RotateFlip(RotateFlipType.RotateNoneFlipNone);
break;
}
}
This code removes the EXIF Orientation Tag properly.
And saving the image works is i simply use img.save
But the app provides user the ability to select the format of the image.For that i use the following code
private void saveJpeg(string path, Bitmap img, long quality)
{
EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
ImageCodecInfo Codec = this.getEncoderInfo(imgformat);
if (Codec == null)
return;
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
img.Save(path + ext, Codec, encoderParams);
}
public string getimgext(string ccodec)
{
if (ccodec.Equals("image/png"))
{
return ".png";
}
else if (ccodec.Equals("image/jpeg"))
{
return ".jpg";
}
else if (ccodec.Equals("image/tiff"))
{
return ".tif";
}
else if (ccodec.Equals("image/bmp"))
{
return ".bmp";
}
else if (ccodec.Equals("image/gif"))
{
return ".gif";
}
else
{
return null;
}
}
private ImageCodecInfo getEncoderInfo(string mimeType)
{
// Get image codecs for all image formats
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
// Find the correct image codec
for (int i = 0; i < codecs.Length; i++)
if (codecs[i].MimeType == mimeType)
return codecs[i];
return null;
}
When i save the image with SaveJpeg the image gets saved with wrong orientation.What im i doing wrong? Please help.
UPDATE:
I have modified the method so that i dont need to create a new instance of the bitmap as the loop processes many files.But this does not work unless i create a new instance of the bitmap.This process consumes an additional of 10+ seconds of the processing time when compared to the old version.
Im using the code like this
image = (Bitmap)FixImageOrientation(Bitmap.FromFile(path));
Image FixImageOrientation(Image srce)
{
const int ExifOrientationId = 0x112;
// Read orientation tag
if (!srce.PropertyIdList.Contains(ExifOrientationId)) return srce;
var prop = srce.GetPropertyItem(ExifOrientationId);
var orient = BitConverter.ToInt16(prop.Value, 0);
// Force value to 1
prop.Value = BitConverter.GetBytes((short)1);
srce.SetPropertyItem(prop);
// Rotate/flip image according to <orient>
switch (orient)
{
case 1:
srce.RotateFlip(RotateFlipType.RotateNoneFlipNone);
return srce;
case 2:
srce.RotateFlip(RotateFlipType.RotateNoneFlipX);
return srce;
case 3:
srce.RotateFlip(RotateFlipType.Rotate180FlipNone);
return srce;
case 4:
srce.RotateFlip(RotateFlipType.Rotate180FlipX);
return srce;
case 5:
srce.RotateFlip(RotateFlipType.Rotate90FlipX);
return srce;
case 6:
srce.RotateFlip(RotateFlipType.Rotate90FlipNone);
return srce;
case 7:
srce.RotateFlip(RotateFlipType.Rotate270FlipX);
return srce;
case 8:
srce.RotateFlip(RotateFlipType.Rotate270FlipNone);
return srce;
default:
srce.RotateFlip(RotateFlipType.RotateNoneFlipNone);
return srce;
}
}
In one method you have argument of type Image but in other Bitmap. So I'm guessing that you convert source JPEG image to Bitmap before call FixImageOrientation.
This will work:
var jpeg = Image.FromFile("original.jpg");
FixImageOrientation(jpeg);
var bitmap = new Bitmap(jpeg);
saveJpeg("new",bitmap,1);
This won't:
var jpeg = Image.FromFile("original.jpg");
var bitmap = new Bitmap(jpeg);
FixImageOrientation(bitmap);
saveJpeg("new", bitmap, 1);

C64 loading screen thoughts

I have made a loading screen (splash screen) just like the old C64.
I have used a series of picture boxes and just change the coloured image using a timer and a case statement.
switch (a)
{
case 1:
pictureBox1.Image = Properties.Resources.image1;
pictureBox8.Image = Properties.Resources.image1;
pictureBox10.Image = Properties.Resources.image1;
pictureBox2.Image = Properties.Resources.image1;
pictureBox11.Image = Properties.Resources.image1;
pictureBox9.Image = Properties.Resources.image1;
break;
case 2:
pictureBox1.Image = Properties.Resources.image2;
pictureBox8.Image = Properties.Resources.image2;
pictureBox10.Image = Properties.Resources.image2;
break;
case 3:
pictureBox1.Image = Properties.Resources.image3;
pictureBox8.Image = Properties.Resources.image3;
pictureBox10.Image = Properties.Resources.image3;
break;
case 4:
pictureBox1.Image = Properties.Resources.image4;
pictureBox8.Image = Properties.Resources.image4;
break;
case 5:
pictureBox1.Image = Properties.Resources.image5;
pictureBox8.Image = Properties.Resources.image5;
break;
case 6:
pictureBox1.Image = Properties.Resources.image6;
pictureBox8.Image = Properties.Resources.image6;
break;
case 7:
pictureBox1.Image = Properties.Resources.image7;
pictureBox8.Image = Properties.Resources.image7;
break;
case 8:
pictureBox1.Image = Properties.Resources.image8;
pictureBox8.Image = Properties.Resources.image8;
break;
}
its a bit nasty looking, how could I improve my code?
You could have a look at the Iterator design pattern. You could create a class that represents a single stage, that class would have properties for each of the picture boxes and you would set the value of those properties to the relevant item in your resources file.
You then create instances of that object for each loading stage, put them in a collection and write an iterator to loop that collection.
There are a two things I'd improve:
Store your images in an array, so you don't have to repeat case X/imageX every time.
Handle the common stuff first, then concentrate on the special cases.
You can declare the array in your form as a "fake" constant, since it won't change:
private readonly static Image[] myImages = new[] {
Properties.Resources.image1,
Properties.Resources.image2,
Properties.Resources.image3,
Properties.Resources.image4,
Properties.Resources.image5,
Properties.Resources.image6,
Properties.Resources.image7,
Properties.Resources.image8
}
and then use the following code in your Timer hander:
Image image = myImages[a-1];
pictureBox1.Image = image;
pictureBox8.Image = image;
// special cases
if (a == 1)
{
pictureBox2.Image = image;
pictureBox11.Image = image;
pictureBox9.Image = image;
}
if (a >= 1 && a <= 3)
{
pictureBox10.Image = image;
}

Dynamic random call to image elements to XAML from C#

I have the following code in C#. A function by which I want to highlight one of the nine images at random. The code is as follows,
public void randomize(object sender, MouseButtonEventArgs e)
{
String img = "image";
int random = RandomNumber(10, 18); //Generate Random Number
score.Content = random;
img += random; //append generated number to "image"
//Call function to highlight behind image
ToGold(random);
}
I tried to make the function call ToGold(random) to be able to dynamically refer to one of the images on XAML. But I was not able to make the code work as I intended. So I took a brute force approach as below,
public void ToGold(int Img)
{
Uri gold = new Uri("/Start;component/Images/gold1.png", UriKind.Relative); //Set Uri path of gold image
ImageSource ImgSrc = new BitmapImage(gold); //Define ImageSource and assign
switch(Img)
{
case 10:
{
image10.Source = ImgSrc;
break;
}
case 11:
{
image11.Source = ImgSrc;
break;
}
case 12:
{
image12.Source = ImgSrc;
break;
}
case 13:
{
image13.Source = ImgSrc;
break;
}
case 14:
{
image14.Source = ImgSrc;
break;
}
case 15:
{
image15.Source = ImgSrc;
break;
}
case 16:
{
image16.Source = ImgSrc;
break;
}
case 17:
{
image17.Source = ImgSrc;
break;
}
case 18:
{
image18.Source = ImgSrc;
break;
}
}
}
So my question is how do I make the code efficient by making it dynamic? Can anyone please help me?
NOTE: I have just started studying WPF. So please bear with me.
You can use the FindName method on the window to find an element by its name.
Or you could create an array containing your images in order, i.e. { image0, image1, image2, image3, ... } and then access that array with a random index.

how can i apply different color to datapoint of ms chart?

I am working on MS chart, not having so much idea.
I have bind the chart, my next thing is to give different colors of each datapoint?
How can i do that?
My sample code is:
foreach (DataPoint pt in ChartRTM.Series["SeriesSeverity"].Points)
{
string sev = pt.YValues[1].ToString(); // this will be your value depending upon which you could set the color
switch (sev)
{
case "I":
pt.Color = Color.Red;
break;
default:
pt.Color = Color.Blue;
break;
}
}
I think you want to change the Marker color of the point :
To do this, change the switch statement :
switch (sev)
{
case "I":
pt.MarkerColor = Color.Red;
break;
default:
pt.MarkerColor = Color.Blue;
break;
}

Categories