I did program a tcp/ip-chat, which has functions like webcam-chat and screentransfer and something like that.
But the problem is, that it only can receive pictures which size is scaled ...
I will poste the full code of my test-class:
//static Byte[] Ip = {
// 192,
// 168,
// 0,
// 215q
// };
//static IPAddress IpAdress = new IPAddress(Ip);
TcpListener sTCP = new TcpListener(IPAddress.Any, 8000);
TcpClient cTCP;
Byte[] ImageData;
String IP = null;
Int32 Port = 0;
private void close(object sender, FormClosingEventArgs e)
{
sTCP.Stop();
Environment.Exit(Environment.ExitCode);
}
private void Form1_Load(object sender, EventArgs e)
{
Thread listthread = new Thread(new ThreadStart(StartListening));
listthread.Start();
Thread startReceiving = new Thread(new ThreadStart(Listen));
startReceiving.Start();
}
void StartListening()
{
sTCP.Start();
//9123
}
void startsendwebcam(Bitmap img)
{
byte[] s;
byte[] buffer;
cTCP = new TcpClient(IP, Port);
BinaryWriter sWriter = new BinaryWriter(cTCP.GetStream());
buffer = Image2ByteArray(img, System.Drawing.Imaging.ImageFormat.Png);
int cLength = buffer.Length;
s = new byte[cLength];
s = buffer;
sWriter.Write(cLength);
sWriter.Write(s);
sWriter.Flush();
sWriter.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (timer1.Enabled)
{
button3.Text = "Begin";
textBox1.Enabled = true;
timer1.Enabled = false;
}
else
{
String[] split = textBox1.Text.Split(':');
IP = split[0];
Port = Convert.ToInt32(split[1]);
button3.Text = "End";
textBox1.Enabled = false;
timer1.Enabled = true;
}
}
private Bitmap CreateScreenshot(int left, int top, int width, int height)
{
Bitmap bmp = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(left, top, 0, 0, new Size(width, height));
g.Dispose();
return bmp;
}
Bitmap ResizeImage(Bitmap imgToResize, Size size)
{
Bitmap b = new Bitmap(size.Width, size.Height);
using (Graphics g = Graphics.FromImage((Image)b))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, size.Width, size.Height);
}
return b;
}
void Listen()
{
do
{
try
{
if (sTCP.Pending())
{
cTCP = sTCP.AcceptTcpClient();
BinaryReader r = new BinaryReader(cTCP.GetStream());
ImageData = new Byte[r.ReadInt32()];
ImageData = r.ReadBytes(ImageData.Length);
pictureBox1.Image = ByteArray2Image(ImageData);
r.Close();
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}
while (true);
}
public byte[] Image2ByteArray(Image Bild, System.Drawing.Imaging.ImageFormat Bildformat)
{
System.IO.MemoryStream MS = new System.IO.MemoryStream();
Bild.Save(MS, Bildformat);
MS.Flush();
return MS.ToArray();
}
public Image ByteArray2Image(byte[] ByAr)
{
Image img = default(Image);
System.IO.MemoryStream MS = new System.IO.MemoryStream(ByAr);
return Image.FromStream(MS);
}
private void timer1_Tick(object sender, EventArgs e)
{
int quality = trackBar1.Value * 10;
if (quality != 0)
{
startsendwebcam(ResizeImage(CreateScreenshot(0, 0, 800, 800), new Size(quality, quality)));
}
}
}
I can send and receive images over the internet; i did portforwarding;
but it can only receive scaled images.
Is there an possibility to send and receive HD-Pictures?
The current result is;
http://www.directupload.net/file/d/3719/9sel75ej_png.htm
Yay!
I got it!
It can send now a picture with dimensions over 800 over wan!
The server is still with bugs, if anyone is interrested about TCPImageSending I can fix the server...
http://ageofadventure.bplaced.net/WORKING.png
The project:
http://ageofadventure.bplaced.net/TCPIPImageClass.zip
Have fun!
Related
I have created a Form Application to Extracted Image , I have searched many posts , till Now I am able to download into the MemoryStream (Byte Array ).
I am not able to save that byte array into file system and check the image size ....
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public List<string> FetchImages(string Url)
{
List<string> imageList = new List<string>();
if (!Url.StartsWith("http://") && !Url.StartsWith("https://"))
Url = "http://" + Url;
string responseUrl = string.Empty;
string htmlData = ASCIIEncoding.ASCII.GetString(DownloadData(Url, out responseUrl));
if (responseUrl != string.Empty)
Url = responseUrl;
if (htmlData != string.Empty)
{
string imageHtmlCode = "<img";
string imageSrcCode = #"src=""";
int index = htmlData.IndexOf(imageHtmlCode);
while (index != -1)
{
htmlData = htmlData.Substring(index);
int brackedEnd = htmlData.IndexOf('>'); //make sure data will be inside img tag
int start = htmlData.IndexOf(imageSrcCode) + imageSrcCode.Length;
int end = htmlData.IndexOf('"', start + 1);
if (end > start && start < brackedEnd)
{
string loc = htmlData.Substring(start, end - start);
imageList.Add(loc);
}
if (imageHtmlCode.Length < htmlData.Length)
index = htmlData.IndexOf(imageHtmlCode, imageHtmlCode.Length);
else
index = -1;
}
for (int i = 0; i < imageList.Count; i++)
{
string img = imageList[i];
string baseUrl = GetBaseURL(Url);
if ((!img.StartsWith("http://") && !img.StartsWith("https://"))
&& baseUrl != string.Empty)
img = baseUrl + "/" + img.TrimStart('/');
imageList[i] = img;
}
}
return imageList;
}
private byte[] DownloadData(string Url)
{
string empty = string.Empty;
return DownloadData(Url, out empty);
}
private byte[] DownloadData(string Url, out string responseUrl)
{
byte[] downloadedData = new byte[0];
try
{
WebRequest req = WebRequest.Create(Url);
WebResponse response = req.GetResponse();
Stream stream = response.GetResponseStream();
responseUrl = response.ResponseUri.ToString();
byte[] buffer = new byte[1024];
MemoryStream memStream = new MemoryStream();
while (true)
{
int bytesRead = stream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
break;
}
else
{
memStream.Write(buffer, 0, bytesRead);
}
}
downloadedData = memStream.ToArray();
stream.Close();
memStream.Close();
}
catch (Exception)
{
responseUrl = string.Empty;
return new byte[0];
}
return downloadedData;
}
private Image ImageFromURL(string Url)
{
byte[] imageData = DownloadData(Url);
Image img = null;
try
{
MemoryStream stream = new MemoryStream(imageData);
img = Image.FromStream(stream);
stream.Close();
}
catch (Exception)
{
}
return img;
}
private string GetBaseURL(string Url)
{
int inx = Url.IndexOf("://") + "://".Length;
int end = Url.IndexOf('/', inx);
string baseUrl = string.Empty;
if (end != -1)
return Url.Substring(0, end);
else
return string.Empty;
}
private void btnGetImages_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
listImages.Items.Clear();
foreach (string image in FetchImages(txtURL.Text))
{
listImages.Items.Add(image);
}
this.Cursor = Cursors.Default;
}
private void btnView_Click(object sender, EventArgs e)
{
if (listImages.SelectedIndex != -1)
picImage.Image = ImageFromURL(listImages.SelectedItem.ToString());
}
private void btnSave_Click(object sender, EventArgs e)
{
}
private void btnDownload_Click(object sender, EventArgs e)
{
DownloadData(txtURL.Text);
}
.. I am trying to save the memroy stream into hard drive but still not getting exact code ,
i think this code needs some additional changes
MemoryStream memStream = new MemoryStream();
while (true)
{
//Try to read the data
int bytesRead = stream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
break;
}
else
{
//Write the downloaded data
memStream.Write(buffer, 0, bytesRead);
}
}
Any Help will be appreciated
If you want to save the Byte[] array to a file,
Syntax : File.WriteAllBytes(string path, byte[] bytes)
Eg : File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO
refer this link for more info http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx
If you want to convert the Byte back to image and save to the drive.
Eg:
byte[] bitmap = YourImage();
using(Image image = Image.FromStream(new MemoryStream(bitmap)))
{
image.Save("image.jpg", ImageFormat.Jpeg);
}
I want my server to keep listening the the same client. It listen the client only one time. How can i keep reading the data sent from client side.
sk = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
sk.Bind(new IPEndPoint(IPAddress.Any, 5000));
sk.Listen(-1);
while (true)
{
try
{
Socket client = sk.Accept();
NetworkStream ns = new NetworkStream(client);
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = ns.Read(buffer, 0, buffer.Length);
if (read <= 0)
break;
ms.Write(buffer, 0, read);
}
}
MemoryStream msi = new MemoryStream(buffer);
Image returnImage = Image.FromStream(msi);
}
catch (Exception)
{
}
}
Finally i found a way to this problem
private void Form1_Load(object sender, EventArgs e)
{
serverSocket = new TcpListener(9361);
clientSocket = default(TcpClient);
Thread listen = new Thread(listenClients);
listen.Start();
}
//this will keep listening the clients
public void listenClients()
{
int counter = 0;
serverSocket.Start();
counter = 0;
while ((true))
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
Thread thread = new Thread(
() => readClient(clientSocket));
thread.Start();
}
}
public void broadcast(Image bmp)
{
pictureBox1.Image = bmp;
} //en
//keep reading the client data
private void readClient(TcpClient inClientSocket)
{
byte[] bytesFrom = new byte[65536];
string dataFromClient = null;
while ((true))
{
try
{
NetworkStream networkStream = inClientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
MemoryStream ms = new MemoryStream(bytesFrom);
Image returnImage = Image.FromStream(ms);
broadcast(returnImage);
}
catch (Exception ex)
{
}
} //end while
} //end readClint
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 have write a program that consists server and client. The server makes a screenshot desktop, and the client receives the screenshot and shows on the form. There is a problem in the data transfer, I see only a small strip. I checked before sending the image on the server is ok. However, the client receives the wrong image. What is wrong?
XAML:
<Window x:Class="TestTCP.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TestTCP" Height="350" Width="525">
<Grid>
<Image x:Name="img1" Margin="0"/>
</Grid>
</Window>
Code C#:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Task rec = new Task(WaitClientQuery);
rec.Start();
Task tk = new Task(Send);
tk.Start();
}
private void Send()//server part. take screen and send image
{
Bitmap temp = CaptureScreen(true);
MemoryStream ms3 = new MemoryStream();
BitmapImage image = new BitmapImage();
byte[] img_byte;
try
{
((System.Drawing.Bitmap)temp).Save(ms3, System.Drawing.Imaging.ImageFormat.Bmp);
image.BeginInit();
ms3.Seek(0, SeekOrigin.Begin);
image.StreamSource = ms3;
image.EndInit();
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
img_byte = ms.ToArray();
}
try
{
TcpClient client = new TcpClient("192.168.1.64", 4444);
NetworkStream netstream = client.GetStream();
netstream.Write(img_byte, 0, img_byte.Length);
netstream.Close();
client.Close();
}
catch (Exception)
{
}
}
catch (Exception ee)
{
}
}
[StructLayout(LayoutKind.Sequential)]
struct CURSORINFO
{
public Int32 cbSize;
public Int32 flags;
public IntPtr hCursor;
public POINTAPI ptScreenPos;
}
[StructLayout(LayoutKind.Sequential)]
struct POINTAPI
{
public int x;
public int y;
}
[DllImport("user32.dll")]
static extern bool GetCursorInfo(out CURSORINFO pci);
[DllImport("user32.dll")]
static extern bool DrawIcon(IntPtr hDC, int X, int Y, IntPtr hIcon);
const Int32 CURSOR_SHOWING = 0x00000001;
public static Bitmap CaptureScreen(bool CaptureMouse)
{
Bitmap result = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
try
{
using (Graphics g = Graphics.FromImage(result))
{
g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
if (CaptureMouse)
{
CURSORINFO pci;
pci.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(CURSORINFO));
if (GetCursorInfo(out pci))
{
if (pci.flags == CURSOR_SHOWING)
{
DrawIcon(g.GetHdc(), pci.ptScreenPos.x, pci.ptScreenPos.y, pci.hCursor);
g.ReleaseHdc();
}
}
}
}
}
catch
{
result = null;
}
return result;
}
void WaitClientQuery()//receive data(client)
{
try
{
IPAddress ip ;
IPAddress.TryParse("192.168.1.64", out ip);
TcpListener listener = new TcpListener(ip, 4444);
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
Thread thread = new Thread(new ParameterizedThreadStart(ReadMessage));
thread.IsBackground = true;
thread.Start(client);
}
}
catch (Exception ex)
{
}
}
void ReadMessage(object obj)
{
try
{
TcpClient client = (TcpClient)obj;
NetworkStream netstream = client.GetStream();
byte[] arr = new byte[client.ReceiveBufferSize ];
int len = netstream.Read(arr, 0, client.ReceiveBufferSize);
if (len > 0)
{
try
{
Action act = delegate
{
MemoryStream strmImg = new MemoryStream(arr);
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
myBitmapImage.StreamSource = strmImg;
myBitmapImage.EndInit();
img1.Source = myBitmapImage;
};
this.Dispatcher.BeginInvoke(act);
}
catch (Exception ex)
{
string message = ex.Message;
}
}
netstream.Close();
client.Close();
}
catch (Exception ex)
{
}
}
}
P.S. Result, screen program after compile:
click to view
The main root cause the client.ReceiveBufferSize using default value are 8192 byte so the client will not receive enough image which has been transferred from server. In my code, I would like to see at client receive correctly the size of image so I use BinaryWriter to transfer length of image. From client side I have used BinaryReader to read exactly number of bytes and size of image to save bandwidth. Hope this help
At the Send method:
TcpClient client = new TcpClient("192.168.1.64", 4444);
using (NetworkStream netstream = client.GetStream())
{
using (BinaryWriter bw = new BinaryWriter(netstream))
{
bw.Write(img_byte.Length);
bw.Write(img_byte, 0, img_byte.Length);
}
client.Close();
}
At the ReadMessage(object obj)
private void ReadMessage(object obj)
{
try
{
byte[] arr = null;
TcpClient client = (TcpClient) obj;
using (NetworkStream netstream = client.GetStream())
{
using (BinaryReader br = new BinaryReader(netstream))
{
var arrLen = new byte[4];
br.Read(arrLen, 0, 4);
int len = BitConverter.ToInt32(arrLen, 0);
if (len > 0)
{
arr = new byte[len];
int read = 0;
while (read != len)
{
read += br.Read(arr, read, arr.Length - read);
}
}
}
}
if (arr != null && arr.Length > 0)
{
try
{
Action act = delegate
{
MemoryStream strmImg = new MemoryStream(arr);
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
myBitmapImage.StreamSource = strmImg;
myBitmapImage.EndInit();
img1.Source = myBitmapImage;
};
this.Dispatcher.BeginInvoke(act);
}
catch (Exception ex)
{
string message = ex.Message;
}
}
client.Close();
}
catch (Exception ex)
{
}
}
I expect client.ReceiveBufferSize on client side has wrong information
I would recomend to read data in loop.
if(netstream.CanRead)
{
byte[] myReadBuffer = new byte[1024];
int numberOfBytesRead = 0;
do
{
numberOfBytesRead = netstream.Read(myReadBuffer, 0, myReadBuffer.Length);
}
while(netstream.DataAvailable);
}
and save data into the List or memorystream
Or may be easier way, before your server send all data, send the size
netstream.Write(img_byte.Length); //does not work with NetworkStream
netstream.Write(img_byte, 0, img_byte.Length);
and client can read it first to allocate appropriate buffer.
To send and receive particular data type I would recomend
build BinaryWriter from your NetworkStream
using (BinaryWriter writer = new BinaryWriter(netstream))
I'm receiving from socket communication an image as byte[] and then I try to show it in a pictureBox. When I run the code it shows a message error only saying: "NullReferenceException"
The catch handling the exception is ex1 and I checked and the pic isn't null so I can't figure it out why this exception is happening.
This is my code:
try
{
if (pictureBox1.InvokeRequired)
{
try
{
pic = imageEmp;
addControlHandler c = new addControlHandler(addPic);
this.Invoke(c);
}
catch (Exception exc) { MessageBox.Show(exc.Message); }
}
else
{
pictureBox1.Image = ByteToImage(imageEmp);
}
}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message);
}
public void addPic() //when invokeRequired == true
{
pictureBox1.Image = ByteToImage(pic);
}
Here is the code to convert byte[] to Image:
public Image ByteToImage(byte[] imageBytes) //convert byte[] to image
{
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = new Bitmap(ms);
return image;
}
UPDATE 1: Regarding Hans answer, I make he following changes:
Change my ByteToImage to Hans's answer and to check where the error is I added this lines in the place where this.Invoke(c) was:
if (c != null)
{
try
{
this.Invoke(c);
}
catch (Exception e_c)
{
MessageBox.Show(e_c.Message, "exc from e_c");
}
}
This give me an exception : NullReferenceException
Thanks for any help!
UPDATE 2: Now it's working, I send JPEG images instead of JPG and it show it now. Don't know why this happens but now it's working ok.
Here is an example that you can try I have tested this just now using my own method this works so replace your code with the lines of code in my btnStudentPic_Click let me know if this works for you..
For Compact Framework try this instead
public static byte[] ReadAllBytes(string path)
{
byte[] buffer;
using (FileStream fs = new FileStream(path, FileMode.Open,
FileAccess.Read, FileShare.Read))
{
int offset = 0;
int count = (int)fs.Length;
buffer = new byte[count];
while (count > 0)
{
int bytesRead = fs.Read(buffer, offset, count);
offset += bytesRead;
count -= bytesRead;
}
}
return buffer;
}
//Windows example below don't use for CF
private void btnStudentPic_Click(object sender, EventArgs e)
{
Image picture = (Image)BrowseForPicture();
this.picStudent.Image = picture;
this.picStudent.SizeMode = PictureBoxSizeMode.StretchImage;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private Bitmap BrowseForPicture()
{
// Bitmap picture = null;
try
{
if (this.fdlgStudentPic.ShowDialog() == DialogResult.OK)
{
byte[] imageBytes = File.ReadAllBytes(this.fdlgStudentPic.FileName);
StudentPic = new Bitmap( this.fdlgStudentPic.FileName);
StuInfo.StudentPic = imageBytes;
}
else
{
StudentPic = Properties.Resources.NoPhotoAvailable;
}
}
catch (Exception)
{
MessageBox.Show("That was not a picture.", "Browse for picture");
StudentPic = this.BrowseForPicture();
}
return StudentPic;
}