3

What I'm doing here is I'm copying an image file from a terminal to my server using ftp. But when I check the picture in the server it suddenly becomes poor quality image.

I'm starting to think maybe it's because of my conversion from image to byte array. Can anyone help?

Here's my code..

Stream stream = FileUploadPic.FileContent;

System.Drawing.Image i = new Bitmap(stream);

var abort = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

var thumbnail = i.GetThumbnailImage(300, 300, abort, IntPtr.Zero);

byte[] bytes = imageToByteArray(thumbnail);

FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(path);

request.Method = WebRequestMethods.Ftp.UploadFile;

request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
request.ContentLength = bytes.Length;
Stream req_Stream = request.GetRequestStream();
req_Stream.Write(bytes, 0, bytes.Length);
req_Stream.Close();

FtpWebResponse response = (FtpWebResponse)request.GetResponse();

This is the imageToByteArray function:

public byte[] imageToByteArray(System.Drawing.Image imageIn) { 
    MemoryStream ms = new MemoryStream(); 
    imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); 
    return ms.ToArray(); 
}
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272

2 Answers2

5

The loss in quality comes from using GetThumbnailImage. It is only intended to be used in fairly specific scenarios, described in the documentation.

This answer describes how to have more fine-tuned control over the quality and characteristics of image output in c#.

Community
  • 1
  • 1
Rex M
  • 142,167
  • 33
  • 283
  • 313
  • thank you rex for your answer. I've tested that part of my code. I've tried saving the thumbnail image to the same terminal and the image is perfectly fine. But whenever I upload it to the server. the image becomes somehow pixelated. – user2272856 Apr 22 '13 at 03:26
3

System.Drawing.Imaging.ImageFormat.Gif is your problem. GIF is a rather old format, and is limited to 256 colours.

If you want to avoid recompressing a Jpeg, I suggest you try ImageFormat.Png, which is a much more modern format, and still loss-less.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272