I have 2 Apps (server - client ) .
The server is modified version of TVsharp (Application that stream local analog tv signal using RTLSDR)
Each frame of the streamed video is a grayscale array of bytes .
I have modified it so it re sizes and sends each frame for a client over TCP socket
The client is supposed to receive the frames through the socket as Image objects and displays them in a picture box
Im getting invalid parameters error .
After i added a delay (Thread.Sleep()) it started to display one frame and then it gives invalid parameter exception (after the sleeping time)
This is the part of TVsharp that dose the sending :
Grayscale is an array that contains the brightness for each pixel
private string drive = "E:\\";
private string file = "0";
private string extension = ".bmp";
private string path2 = "E:\\test\\";
private string fullpath;
private int file_counter = 0;
Bitmap bitmap2 = new Bitmap(_pictureWidth, _pictureHeight);
var data2 = bitmap2.LockBits(new Rectangle(Point.Empty, bitmap2.Size),
ImageLockMode.WriteOnly,PixelFormat.Format24bppRgb);
Marshal.Copy(GrayScaleValues, 0, data2.Scan0, GrayScaleValues.Length);
bitmap2.UnlockBits(data2);
bitmap2.Save(fullpath, System.Drawing.Imaging.ImageFormat.Bmp);
string Npath = path2 + file + extension;
Image img = Image.FromFile(fullpath);
// Size size = new Size(982, 543);
// ResizeImage(img, size);
Rectangle cropRect = new Rectangle(80, 0, 240, 175);
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
using (Graphics g = Graphics.FromImage(target))
{
g.DrawImage(img, new Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel);
}
//double scale = 203 / 96;
int width = (int)(target.Width);
int height = (int)(target.Height);
BinaryWriter brn = new BinaryWriter(s);
System.Drawing.Bitmap bmpScaled = new System.Drawing.Bitmap(target, width, height);
bmpScaled.Save(Npath);
byte[] imageArray = File.ReadAllBytes(Npath);
sw.WriteLine(imageArray.Length.ToString());
sw.Flush();
// Thread.Sleep(500);
brn.Write(imageArray);
//Thread.Sleep(500);
_detectLevel = Convert.ToInt32(_maxSignalLevel * _detectorLevelCoef);
_agcSignalLevel = agcMaxLevel;
}
This client the client segment that suppose to get the frames and display them
flag = true;
TcpClient client = new TcpClient(textBox1.Text, Convert.ToInt32(textBox2.Text));
Stream s = client.GetStream();
StreamReader sr = new StreamReader(s);
StreamWriter sw = new StreamWriter(s);
sw.Flush();
BinaryFormatter formatter = new BinaryFormatter();
string msg = sr.ReadLine();
MessageBox.Show("It's working !! the message is " + msg);
BinaryReader Brn = new BinaryReader(s);
Thread.Sleep(5000);
while (flag)
{
// Thread.Sleep(5000);
int size = Convert.ToInt32(sr.ReadLine());
label3.Text = "Size is " + size;
byte[] imagerray = Brn.ReadBytes(size);
MemoryStream ms = new MemoryStream(imagerray);
Thread.Sleep(10000);
Image image = Image.FromStream(ms);
ResizeImage(image, this.Size);
pictureBox1.Image = image;
Thread.Sleep(10);
}
}
Related
So i try to use ONNX file for local object detection, work great in UWP and WPF with local saved image.
Now, the problem is, to use my detection algorithm with 3D live camera.
My detection algorithm expect a (Windows.Media.)VideoFrame, and my camera give me an (System.Windows.Media.Imaging.)WriteableBitmap.
So here what i have donne already :
Convert my WriteableBitmap to Bitmap :
private System.Drawing.Bitmap BitmapFromWriteableBitmap(System.Windows.Media.Imaging.WriteableBitmap writeBmp)
{
System.Drawing.Bitmap bmp;
using (MemoryStream outStream = new MemoryStream())
{
System.Windows.Media.Imaging.BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create((System.Windows.Media.Imaging.BitmapSource)writeBmp));
enc.Save(outStream);
bmp = new System.Drawing.Bitmap(outStream);
}
return bmp;
}
Now i want to tranform my Bitmap to SoftwareBitmap (for creating a VideoFrame with VideoFrame.CreateWithSoftwareBitmap)
Windows.Storage.Streams.InMemoryRandomAccessStream stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
Stream strm;
private async Task<SoftwareBitmap> SoftWareBitmapFromBitmap(Bitmap bitmap)
{
SoftwareBitmap softwareBitmap2;
strm = stream.AsStream();
bitmap.Save(strm, ImageFormat.Png);
Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
softwareBitmap2 = await decoder.GetSoftwareBitmapAsync();
return softwareBitmap2;
}
But in this last function i got an error in :
bitmap.Save(strm, ImageFormat.Bmp);
I got the "A generic error occurred in GDI+."
I have try to lock/unlock the bitmap, i have try different ImageFormat, if i change to 'ImageFormat.MemoryBmp' i got an "Value cannot be null".
Thank you.
I dont know how to quotes or thumb up answer and sorry for that.
That work great just with : outStream.AsRandomAccessStream()
Here the final function :
public async Task<System.Windows.Shapes.Rectangle> GetPositionDetection(WriteableBitmap wrtBitmap, double imageWidth, double imageHeight)
{
try
{
MemoryStream outStream = new MemoryStream();
System.Windows.Media.Imaging.BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create((System.Windows.Media.Imaging.BitmapSource)wrtBitmap));
enc.Save(outStream);
Windows.Storage.Streams.InMemoryRandomAccessStream stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(outStream.AsRandomAccessStream());
SoftwareBitmap tmp2 = await decoder.GetSoftwareBitmapAsync();
VideoFrame inputImage = VideoFrame.CreateWithSoftwareBitmap(tmp2);
IList<PredictionModel> ResultsList = await objDetec.PredictImageAsync(inputImage);
if (ResultsList.Count == 0)
{
Console.WriteLine("Object not detected");
return null;
}
else
{
var itm = ResultsList.First(x => x.Probability == ResultsList.Max(y => y.Probability));
System.Windows.Shapes.Rectangle rct = new System.Windows.Shapes.Rectangle();
rct.Stroke = System.Windows.Media.Brushes.Red;// new SolidColorBrush(Windows.UI.Colors.Red);
rct.StrokeThickness = 2;
rct.Width = imageWidth * (MappingEchellefloat(0, 1, 0, 100, itm.BoundingBox.Width) / 100);
rct.Height = imageHeight * (MappingEchellefloat(0, 1, 0, 100, itm.BoundingBox.Height) / 100);
Console.WriteLine("Object returned : " + ResultsList.Count);
return rct;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
Thank you for your help.
Here I have some codes for encoding wma audio files..Its works perfectly.but uploading out put file to server ,some error happend.Its shows output file should be meet the
requirements like rate should be in 16000
public void ConvertToWMA(string tempFilePath, string tempFileName, string audioType)
{
WaveFormat form = new WaveFormat(16000, 16, 1);
using (WmaStream str = new WmaStream(tempFilePath + tempFileName, form))
{
string profileData;
using (StreamReader reader = new StreamReader(File.OpenRead("audio.prx")))
{
profileData = reader.ReadToEnd();
}
IWMProfileManager profileManager;
IWMProfile wmProfile = null;
profileManager = WM.CreateProfileManager();
profileManager.LoadProfileByData(profileData, out wmProfile);
WMProfile wmp = new WMProfile(str.Profile);
NAudio.WindowsMediaFormat.WmaWriter ww = new NAudio.WindowsMediaFormat.WmaWriter(new FileStream(#"D:\wma\conv\test.wma", FileMode.Create), form, wmProfile);
byte[] buff = null;
int read = 0;
buff = new byte[form.AverageBytesPerSecond];
read = str.Read(buff, 0, buff.Length);
while ((read > 0))
{
ww.Write(buff, 0, read);
read = str.Read(buff, 0, buff.Length);
}
}
}
how can get rid of this issue.someone please help me..
{
var temp = tempFilePath + tempFileName;
using (var reader = new MediaFoundationReader(temp))
{
// Create a wave format for 16-bit pcm at 8000 samples per second.
int channels = reader.WaveFormat.Channels;
int rate = 8000;
int rawsize = 2;
int blockalign = rawsize * channels; // this is the size of one sample.
int bytespersecond = rate * blockalign;
//MediaFoundationEncoder.enc(reader, "test.mp3");
var midformat =
WaveFormat.CreateCustomFormat(WaveFormatEncoding.Pcm,
rate,
channels,
bytespersecond,
blockalign,
rawsize * 8);
// And a conversion stream to turn input into 16-bit PCM.
//var midstream = new MediaFoundationResampler(reader, midformat);
// var outstream = new PcmToALawConversionStream(midstream);
// var outstream = new PcmToALawConversionStream(midstream);
//var converted16Bit = new SampleToWaveProvider16(mixer);
//
// now for MP3, we need to upsample to 44.1kHz. Use MediaFoundationResampler
using (var resampled = new MediaFoundationResampler(
reader, midformat))
{
var outstream = new PcmToALawConversionStream(resampled);
// var desiredBitRate = 16000; // ask for lowest available bitrate
//MediaFoundationEncoder.EncodeToWma(outstream,
// "mixedtets10.wma", desiredBitRate);
WaveFileWriter.CreateWaveFile("mixedtets10.wma", outstream);
//NAudio.WindowsMediaFormat.WmaWriter ww = new NAudio.WindowsMediaFormat.WmaWriter(new FileStream(#"D:\wma\conv\test1.wma", FileMode.Create), midformat, outstream);
}
// NAudio.WindowsMediaFormat.WmaWriter ww = new NAudio.WindowsMediaFormat.WmaWriter(new FileStream(#"D:\wma\conv\test1.wma", FileMode.Create), midformat, outstream);
//NAudio.WindowsMediaFormat.WmaWriter Ww=
// The output stream is our custom stream.
//var outstream = new PcmToALawConversionStream(midstream);
}
}
I'm making an c# and Windows Forms (Classic Windows app like notepad, paint etc.) app that has a feature to get screenshot and send it via mail.
However, It can only take 6 pictures now (I can add more, but I don't want to add more code, I want to make it programmatically), how can I make it send more or less, as set by user, outside of app?
Timer1 sends mail.
Timer2 takes screenshot.
resimoran is an int which is image ratio of resizing, it's 1 by default.
counter is an int,
It's working right now...
here is my code:
private Bitmap Screenshot()
{
Bitmap Screenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics GFX = Graphics.FromImage(Screenshot);
GFX.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size);
return Screenshot;
}
void SendReport()
{
MailMessage mail;
var fromAddress = new MailAddress(frommail, fromname);
var toAddress = new MailAddress(alici, aliciname);
string fromPassword = mailpass;
var smtp = new SmtpClient
{
Host = mailhostaddress,
Port = mailport,
EnableSsl = sslenabled,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = usedefaultcre,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (mail = new MailMessage(fromAddress, toAddress)
{
Subject = konu + DateTime.Now,
Body = "None of your businness!"
})
{
mail.Attachments.Add(attach1);
mail.Attachments.Add(attach2);
mail.Attachments.Add(attach3);
mail.Attachments.Add(attach4);
mail.Attachments.Add(attach5);
mail.Attachments.Add(attach6);
smtp.Send(mail);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
SendReport();
}
private void timer2_Tick(object sender, EventArgs e)
{
counter++;
if (counter == 1)
{
Bitmap ekrangor = Screenshot();
Bitmap imagee = resizeImage(ekrangor, new Size(ekrangor.Width / resimoran, ekrangor.Height / resimoran));
imagee.Save(#"screen1.jpg");
System.IO.Stream streamer = new System.IO.MemoryStream();
imagee.Save(streamer, System.Drawing.Imaging.ImageFormat.Jpeg);
streamer.Position = 0;
attach1 = new Attachment(streamer, "screen1.jpg");
}
else if (counter == 2)
{
Bitmap ekrangor = Screenshot();
Bitmap imagee = resizeImage(ekrangor, new Size(ekrangor.Width / resimoran, ekrangor.Height / resimoran));
imagee.Save(#"screen2.jpg");
System.IO.Stream streamer = new System.IO.MemoryStream();
imagee.Save(streamer, System.Drawing.Imaging.ImageFormat.Jpeg);
streamer.Position = 0;
attach2 = new Attachment(streamer, "screen2.jpg");
}
else if (counter == 3)
{
Bitmap ekrangor = Screenshot();
Bitmap imagee = resizeImage(ekrangor, new Size(ekrangor.Width / resimoran, ekrangor.Height / resimoran));
imagee.Save(#"screen3.jpg");
System.IO.Stream streamer = new System.IO.MemoryStream();
imagee.Save(streamer, System.Drawing.Imaging.ImageFormat.Jpeg);
streamer.Position = 0;
attach3 = new Attachment(streamer, "screen3.jpg");
}
else if (counter == 4)
{
Bitmap ekrangor = Screenshot();
Bitmap imagee = resizeImage(ekrangor, new Size(ekrangor.Width / resimoran, ekrangor.Height / resimoran));
imagee.Save(#"screen4.jpg");
System.IO.Stream streamer = new System.IO.MemoryStream();
imagee.Save(streamer, System.Drawing.Imaging.ImageFormat.Jpeg);
streamer.Position = 0;
attach4 = new Attachment(streamer, "screen4.jpg");
}
else if (counter == 5)
{
Bitmap ekrangor = Screenshot();
Bitmap imagee = resizeImage(ekrangor, new Size(ekrangor.Width / resimoran, ekrangor.Height / resimoran));
imagee.Save(#"screen5.jpg");
System.IO.Stream streamer = new System.IO.MemoryStream();
imagee.Save(streamer, System.Drawing.Imaging.ImageFormat.Jpeg);
streamer.Position = 0;
attach5 = new Attachment(streamer, "screen5.jpg");
}
else if (counter == 6)
{
Bitmap ekrangor = Screenshot();
Bitmap imagee = resizeImage(ekrangor, new Size(ekrangor.Width / resimoran, ekrangor.Height / resimoran));
imagee.Save(#"screen6.jpg");
System.IO.Stream streamer = new System.IO.MemoryStream();
imagee.Save(streamer, System.Drawing.Imaging.ImageFormat.Jpeg);
streamer.Position = 0;
attach6 = new Attachment(streamer, "screen6.jpg");
counter = 0;
}
}
public static Bitmap resizeImage(Bitmap imgToResize, Size size)
{
return (new Bitmap(imgToResize, size));
}
And, please, give me answers in C#, not in English! (not "do this: MSDN bla bla", but "try this void lolnocodezhere() {}")
List<T> is your friend.
you declare it at a proper place as
List<Attachment> attachments = new List<Attachment>();
Then you replace your 6 blocks with a single one where you do a
attachments.Add(new Attachment(streamer, "screen.jpg");)
and when the right time has come you do a
foreach(Attachment a in attachments ) mail.Attachments.Add(a);
After successfully sending the mail you delete the collection like this:
attachments.Clear();
It is up to you to control things like counters, the screen images etc.
Btw: mail.Attachmentsis just such a collection and maybe you want to use it directly..?
I am in the process of uploading images to Amazon S3, however i keep getting the error "Please specify either a Filename, provide a FileStream or provide a ContentBody to PUT an object into S3."
Basically i am uploading an image from a fileupload control and then hitting the code below. It uploads locally fine, but not to Amazon. The Credentials are alright so it only errors when it comes to uplaoding.
Can anyone see why this is happening please?
protected void uploadImg(int prodId, int prodFormat)
{
if (imgPack.HasFile)
{
string fileExt = Path.GetExtension(imgPack.PostedFile.FileName);
string filename = "img" + prodId + ".jpg";
// Specify the upload directory
string directory = Server.MapPath(#"\images\packshots\");
if (fileExt == ".jpeg" || fileExt == ".jpg" || fileExt == ".png")
{
if (packUK.PostedFile.ContentLength < 716800)
{
// Create a bitmap of the content of the fileUpload control in memory
Bitmap originalBMP = new Bitmap(packUK.FileContent);
// Calculate the new image dimensions
decimal origWidth = originalBMP.Width;
decimal origHeight = originalBMP.Height;
decimal sngRatio = origHeight / origWidth;
int newHeight = 354; //hight in pixels
decimal newWidth_temp = newHeight / sngRatio;
int newWidth = Convert.ToInt16(newWidth_temp);
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
// Save the new graphic file to the server
string accessKey = "KEY HERE";
string secretKey = "KEY HERE";
AmazonS3 client;
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey))
{
PutObjectRequest request = new PutObjectRequest();
request.BucketName="MyBucket";
request.CannedACL = S3CannedACL.PublicRead;
request.Key = "images/" + filename;
S3Response response = client.PutObject(request);
}
//newBMP.Save(directory + filename);
// Once finished with the bitmap objects, we deallocate them.
originalBMP.Dispose();
newBMP.Dispose();
oGraphics.Dispose();
}
}
else
{
notifybar.Attributes.Add("style", "display:block;");
notifybar.Attributes.Add("class", "failed");
notifyText.Text = "Error Text Here";
}
}
else
{
notifybar.Attributes.Add("style", "display:block;");
notifybar.Attributes.Add("class", "failed");
notifyText.Text = "Error Text Here";
}
}
You need to assign File or InputStream property of PutObjectRequest object. The code fragment should look like this one:
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey))
{
var stream = new System.IO.MemoryStream();
originalBMP.Save(stream, ImageFormat.Bmp);
stream.Position = 0;
PutObjectRequest request = new PutObjectRequest();
request.InputStream = stream;
request.BucketName="MyBucket";
request.CannedACL = S3CannedACL.PublicRead;
request.Key = "images/" + filename;
S3Response response = client.PutObject(request);
}
Technologies: Visual Studio 2010 and Crystal Reports, MVC3 Web Application, multi tier app.
My web app build one report to label print. The report works fine but not generates the bar code. When I view the report the barcode field is blank. I already installed the IDAutomationHC39M and works in winforms project.
The code that generates the report:
public void Barcode()
{
BarCode report = new BarCode();
Barcodes barcodeDetails = new Barcodes();
DataTable dataTable = barcodeDetails._Barcodes;
for (int i = 0; i < 80; i++)
{
DataRow row = dataTable.NewRow();
string nome = "nome" + i;
decimal preco = i;
string barcode = i + "ADF" + i;
row["nome"] = nome;
row["preco"] = preco;
row["barcode"] = barcode;
dataTable.Rows.Add(row);
}
report.Database.Tables["Barcodes"].SetDataSource((DataTable)dataTable);
report.ExportToHttpResponse(ExportFormatType.PortableDocFormat, System.Web.HttpContext.Current.Response, false, "crReport");
}
Is more easy transform the barcode in a jpeg? If yes, how can i make this in crystal reports?
EDI I: I try change the code for:
for (int i = 0; i < 80; i++)
{
DataRow row = dataTable.NewRow();
string nome = "nome" + i;
decimal preco = i;
string barcode = "*" + i + "ADF" + i + "*";
row["nome"] = nome;
row["preco"] = preco;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
using (Bitmap bitMap = new Bitmap(barcode.Length * 40, 80))
{
using (Graphics graphics = Graphics.FromImage(bitMap))
{
Font oFont = new Font("IDAutomationHC39M", 10);
PointF point = new PointF(2f, 2f);
SolidBrush blackBrush = new SolidBrush(Color.Black);
SolidBrush whiteBrush = new SolidBrush(Color.White);
graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
graphics.DrawString("*" + barcode + "*", oFont, blackBrush, point);
}
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
row["barcode"] = imgBarCode.ImageUrl;
}
}
dataTable.Rows.Add(row);
}
But no effects.
The process to display barcodes in asp.net app (MVC in my case) is really transform the font in an jpeg.
Step 1: get the value for barcode and add "*" in start and end, then creates the Bitmap, Font and Graphics.
DataRow row = dataTable.NewRow();
string barcode = "*" + ID.ToString() + VALOR_VENDA.Value.ToString() + "*";
row["nome"] = NOME_PRODUTO;
row["preco"] = VALOR_VENDA.Value;
int w = barcode.Length * 40;
Bitmap oBitmap = new Bitmap(w, 100);
Graphics oGraphics = Graphics.FromImage(oBitmap);
Font oFont = new Font("IDAutomationHC39M", 18);
PointF oPoint = new PointF(2f, 2f);
SolidBrush oBrushWrite = new SolidBrush(Color.Black);
SolidBrush oBrush = new SolidBrush(Color.White);
oGraphics.FillRectangle(oBrush, 0, 0, w, 100);
oGraphics.DrawString(barcode, oFont, oBrushWrite, oPoint);
Next use an MemoryStream to add the bitmap. Make sure that your dataset field is the type Byte[]. With the memorystream add to dataset the value .ToArray();
using (MemoryStream ms = new MemoryStream())
{
oBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] byteImage = ms.ToArray();
row["barcode"] = byteImage;
}
dataTable.Rows.Add(row);