ArgumentException "parameter is incorrect" - c#

I'm trying to make a code that converts memorystream to a png image, but I'm getting a ArgumentException "parameter is incorrect" error on using(Image img = Image.FromStream(ms)). It doesn't specify it any further so I don't know why I'm getting the error and what am I supposed to do to it.
Also, how do I use the Width parameter with img.Save(filename + ".png", ImageFormat.Png);? I know I can add parameters and it recognizes "Width", but I have no idea how it should be formatted so visual studio would accept it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
MemoryStream ms = new MemoryStream();
public string filename;
private void button1_Click(object sender, EventArgs e)
{
OpenFile();
}
private void button2_Click(object sender, EventArgs e)
{
ConvertFile();
}
private void OpenFile()
{
OpenFileDialog d = new OpenFileDialog();
if(d.ShowDialog() == DialogResult.OK)
{
filename = d.FileName;
var fs = d.OpenFile();
fs.CopyTo(ms);
}
}
private void ConvertFile()
{
using(Image img = Image.FromStream(ms))
{
img.Save(filename + ".png", ImageFormat.Png);
}
}
}
}

I suspect the problem is with how you're reading the file here:
fs.CopyTo(ms);
You're copying the content of the file into the MemoryStream, but then leaving the MemoryStream positioned at the end of the data rather than the start. You can fix that by adding:
// "Rewind" the memory stream after copying data into it, so it's ready to read.
ms.Position = 0;
You should consider what happens if you click on the buttons multiple times though... and I'd strongly advise you to use a using directive for your FileStream, as currently you're leaving it open.

Related

EmguCV never open ".jpg" file but open only ".tif" files..Why?

I am using EmguCV in Visual Studio 2022 and I am simple trying to read and open my image but it only opens .tif image files not .jpg or any other file...
When I try to open any .jpg file it gives me an exception openCV:index out of bound
Here:
I also debugged it and find something like it is not reading file when I passed it to EmguCV image structure "Image<Bgr,byte> imgFile=new Image<Bgr,byte>(filename)"
while it is loading file from dialogue but not passing forward from this structure.
Here's the Debug SS:
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.Util;
namespace test_EmguCV
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
Image<Bgr, byte> imgFile = new Image<Bgr, byte>(ofd.FileName);
pictureBox1.Image = imgFile.Bitmap;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void exToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Another Imp:
My friend is also doing the same work with me and he is using the same ide same mehtods same references same dll files but his is running fine but not of mine..
I just tried your code snippet in a new Form and I can say that I can successfully load a .jpg image and display it in a PictureBox. Make sure your image is not corrupted in the first place.
Here's my code:
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
Image<Bgr, byte> imgFile = new Image<Bgr, byte>(ofd.FileName);
pictureBox1.Image = imgFile.ToBitmap();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Note that it's imgFile.ToBitmap(), not imgFile.Bitmap()
Also I would suggest you to switch to Mat instead of Image<>. More info from OpenCV docs
With Mat the code to get the image is as easy as:
Mat imgFile = new Mat(ofd.FileName);
More info about Mat in EmguCV here

How to properly take image and save image?

I made a Win-Forms application and want to Read a Image from the Webcam and save it to the disk and show it in a picture box. Everything works fine, but when i call the "Capture_Image()" function several times (on button14-click) i get a Error like "Object already in use"
using System;
using System.IO;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Runtime.InteropServices;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
private VideoCapture capture = null;
private Bitmap tempImg = null;
public Form1()
{
InitializeComponent();
capture = new VideoCapture();
}
public void Capture_Image()
{
try
{
capture.Start();
tempImg = capture.QueryFrame().Bitmap;
pictureBox2.Image = tempImg;
pictureBox2.Refresh();
tempImg.Save("C:/FHT59N3/Bildanalyse_Projekt/image.jpg",
System.Drawing.Imaging.ImageFormat.Jpeg);
capture.Stop();
}
catch (NullReferenceException)
{
string message = "No Camera found";
string title = "Please connect Camera";
MessageBoxButtons buttons = MessageBoxButtons.OK;
MessageBox.Show(message, title, buttons, MessageBoxIcon.Warning);
}
}
private void button14_Click(object sender, EventArgs e)
{
Capture_Image();
}
Am i doing something wrong with the capture? Why do i get this error

c# importing excel to datagridview doesn't work

I am using ExcelDataReader here.
I don't know why below code doesn't work.
It doesn't generate any error but it still doesn't show excel data.
It simply doesn't do anything after loading excel file.
I am new to C# and after 5 hours of digging I feel frustrated since I don't know why this doesn't work.
using Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication5
{
public partial class ExcelForm : Form
{
public ExcelForm()
{
InitializeComponent();
}
private void ExcelForm_Load(object sender, EventArgs e)
{
}
DataSet result;
private void btnOpen_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel(.xls)|*.xls|Excel(.xlsx)|*.xlsx", ValidateNames = true })
{
if(ofd.ShowDialog() == DialogResult.OK)
{
FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
IExcelDataReader reader;
if (ofd.FilterIndex == 1)
reader = ExcelReaderFactory.CreateBinaryReader(fs);
else
reader = ExcelReaderFactory.CreateOpenXmlReader(fs);
reader.IsFirstRowAsColumnNames = true;
result = reader.AsDataSet();
reader.Close();
dataGridView.DataSource = result;
}
}
}
}
}
dataGridView.DataSource = DtSet.Tables[0];

Compress Audio upon writing to file

I am trying to create a recorder from audio coming out from soundcard and this is my progress so far, the problem is the recorded audio when saving to file is so large like a song can reach up to hundreds of megabyte.
here's my code
using NAudio.CoreAudioApi;
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Record_From_Soundcard
{
public partial class frmMain : Form
{
private WaveFileWriter writer;
private WasapiLoopbackCapture waveInSel;
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
MMDeviceEnumerator deviceEnum = new MMDeviceEnumerator();
MMDeviceCollection deviceCol = deviceEnum.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);
cboAudioDrivers.DataSource = deviceCol.ToList();
}
private void btnStopRecord_Click(object sender, EventArgs e)
{
waveInSel.StopRecording();
writer.Close();
}
private void btnStartRecord_Click(object sender, EventArgs e)
{
using (SaveFileDialog _sfd = new SaveFileDialog())
{
_sfd.Filter = "Mp3 File (*.mp3)|*.mp3";
if (_sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
MMDevice _device = (MMDevice)cboAudioDrivers.SelectedItem;
waveInSel = new WasapiLoopbackCapture(_device);
writer = new WaveFileWriter(_sfd.FileName, waveInSel.WaveFormat);
waveInSel.DataAvailable += (n, m) =>
{
writer.Write(m.Buffer, 0, m.BytesRecorded);
};
waveInSel.StartRecording();
}
}
}
}
}
can anyone help me on how to compress audio upon saving?
maybe it will be added on this part
waveInSel.DataAvailable += (n, m) =>
{
writer.Write(m.Buffer, 0, m.BytesRecorded);
};
Thanks in advance.. ;)
Try this using naudio dll
Using NAudio.Wave; Using NAudio.Wave.SampleProviders;Using NAudio.Lame
Private void WaveToMP3(int bitRate = 128){
String waveFileName = Application.StartupPath + #"\Temporal\mix.wav";
String mp3FileName = Application.StartupPath + #"\Grabaciones\ " + Strings.Format(DateTime.Now, "dd-MM-yyyy.HH.mm.ss") + ".mp3";
Using (var reader = New AudioFileReader(waveFileName))
{
Using (var writer = New LameMP3FileWriter(mp3FileName, reader.WaveFormat, bitRate))
{
reader.CopyTo(writer);
}
reader.Close();
}
}
You can't make an MP3 file by saving a WAV file with a .MP3 extension (which is what you are doing here). You will need to select an encoder available on your machine, and pass the audio through that. I go into some detail about how to do this with NAudio in this article.

Get ONLY word count from PDF document

I was hoping to get just the word count from a pdf document programmatically.
I've looked at PDFSharp, but it's awefully bulky for what I want to do. I don't have access to the server, so I can't install acrobat to get to their api's or anything. I'd be willing to do it in iTextSharp or another tool.
iTextSharp has a wonderful PdfTextExtractor object that will get you all of the text (assumming as #Rob A pointed out that its actually stored as text and not images or pure vector). Once you've got all of the text a simple RegEx will give you the word count.
The code below should do it for you. (Tested on iText 5.1.1.0)
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 iTextSharp.text.pdf.parser;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string InputFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Input.pdf");
//Get all the text
string T = ExtractAllTextFromPdf(InputFile);
//Count the words
int I = GetWordCountFromString(T);
}
public static string ExtractAllTextFromPdf(string inputFile)
{
//Sanity checks
if (string.IsNullOrEmpty(inputFile))
throw new ArgumentNullException("inputFile");
if (!System.IO.File.Exists(inputFile))
throw new System.IO.FileNotFoundException("Cannot find inputFile", inputFile);
//Create a stream reader (not necessary but I like to control locks and permissions)
using (FileStream SR = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
//Create a reader to read the PDF
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(SR);
//Create a buffer to store text
StringBuilder Buf = new StringBuilder();
//Use the PdfTextExtractor to get all of the text on a page-by-page basis
for (int i = 1; i <= reader.NumberOfPages; i++)
{
Buf.AppendLine(PdfTextExtractor.GetTextFromPage(reader, i));
}
return Buf.ToString();
}
}
public static int GetWordCountFromString(string text)
{
//Sanity check
if (string.IsNullOrEmpty(text))
return 0;
//Count the words
return System.Text.RegularExpressions.Regex.Matches(text, "\\S+").Count;
}
}
}
You can use a pdf2text tool and then count the words:
tools pdf2text

Categories

Resources