Where does this quality loss on Images come from? - c#

in my Winforms application which is connected to a database via Linq to SQL I am saving images (always *.png) to a table which looks like this:
CREATE TABLE [dbo].[Images] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Bild] IMAGE NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Before I can store a picture I have to convert it to byte[] and this is how I do it:
public static byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using (MemoryStream ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
}
Afterwards if I want to load this very same image to a PictureBox in my application I convert it back with this method:
public static Image ByteArrayToImage(byte[] byteArrayIn)
{
using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}
It actually works, the only problem appears when I try to display an Image from the database in a Picturebox.
So when I load this Image to the database:
and later I try to display it. It suddenly looks like this:
I already tried all the possible SizeMode settings for the PictureBox (Normal, Stretchimage, AutoSize,CenterImage,Zoom) and it still looks like this.
Also here is how I load the Images from the database to the pictureBox:
First I retrieve the all the Images belonging to a set via id:
public static ImageList GetRezeptImages(int rezeptId)
{
using (CookBookDataContext ctx = new CookBookDataContext(ResourceFile.DBConnection))
{
IEnumerable<RezeptBilder> bilder = from b in ctx.RezeptBilders where b.FKRezept == rezeptId select b;
ImageList imageList = new ImageList();
foreach(RezeptBilder b in bilder)
{
imageList.Images.Add(Helper.ByteArrayToImage(b.Bild.ToArray()));
}
return imageList;
}
}
Also in my application I have a datagridview where Id's are stored in the first column. So when I want to retrieve any Images belonging to the set I do it like this:
private void dgvRezeptListe_CellClick(object sender, DataGridViewCellEventArgs e)
{
pbRezeptBild.Image = DBManager.GetRezeptImages(Int32.Parse(dgvRezeptListe.SelectedRows[0].Cells[0].Value.ToString())).Images[0];
}
When loaded from a local directory the Image looks fine in the pictureBox. I also tried to convert the initial picture to binary and back (without loading it to the database), it still looked fine when displayed in the pictureBox.
There is something else I realized while debugging the Image which came from the database. When looking into the ImageSize, width and height had both the value 16. This is weird because the original image has totally different dimensions.
Any ideas?

It appears that ImageList is converting your images to MemoryBmp's when you are adding them in GetRezeptImages to the list.
I am not aware as to why it would do that, but that is the reason for your loss of quality in the image. As you also realised, the image is converted to a 16x16 image and then when that is resized in your PictureBox to the original size, it just looks more cheesy.
Edit:
From TaW's comment: The ImageList collection cannot handle varying sized images, so it is converting all the images to a common size. Since there is no size set, it seems it defaults to 16x16.
I would recommend that you change the GetRezeptImages method to return a List<Image> instead of an ImageList and use that accordingly to show the images.
Alternatively, if you will always use the GetRezeptImages method in the same way that you showed in your question, you can change it to always just return the first image in an Image object and entirely throw away all the lists.

ImageList is nice for what it can do: Store lots of Images without losing GDI resources.
But what it can't do is what you probably need: Store images of varying sizes & proportions.
You can and should set it Imagesize and ColorDepth properties (look at the defaults, that are clearly meant for use as a StateImageList; 16x16px and 8bit depth is even bad for a LargeImageList..) but you can't use it if your images need to have different sizes & proportions..
If they don't, that is if they can share at least their proportions, just fix the ImageList by picking a nice size and you're set! All Images you add to the ImageList will automatically be scaled to that Size and converted to the ColorDepth.
Otherwise replace it by a List<Image> or List<Bitmap>..!
If you know the common size and ColorDepth of your Images you can do that:
using (CookBookDataContext ctx = new CookBookDataContext(ResourceFile.DBConnection))
{
IEnumerable<RezeptBilder> bilder =
from b in ctx.RezeptBilders where b.FKRezept == rezeptId select b;
ImageList imageList = new ImageList();
imageList.ColorDepth = ColorDepth.Depth24Bit; //
imageList.ImageSize = yourImageSize; //
foreach(RezeptBilder b in bilder)
{
imageList.Images.Add(Helper.ByteArrayToImage(b.Bild.ToArray()));
}
return imageList;
}
You can either not use an ImageList but a List<Image> or List<Bitmap> instead or make
them - that is: Trim them to the same proportion, basically not much more than a few extra lines..:
Bitmap expandCanvas(Bitmap bmp, Size size)
{
float f1 = 1f * bmp.Width / bmp.Height;
float f2 = 1f * size.Width / size.Height;
Size newSize = size;
if (f1 > f2) newSize = new Size(bmp.Width, (int)(bmp.Height * f1));
else if (f1 < f2) newSize = new Size((int)(bmp.Width / f1), bmp.Height);
Bitmap bmp2 = new Bitmap(newSize.Width, newSize.Height);
bmp2.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
Rectangle RDest = new Rectangle(Point.Empty, bmp.Size);
Rectangle RTgt = new Rectangle(Point.Empty, newSize);
using (Graphics G = Graphics.FromImage(bmp2))
{
G.DrawImage(bmp, RDest, RDest, GraphicsUnit.Pixel);
}
return bmp2;
}
This routine expands the image canvas size with transparent pixels to the right or bottom without scaling the pixels, so it should stay losslessly crisp.

Also You might think about converting it to a string64 instead of byte[]. The code is a little cleaner and once it's a string it can be dropped in just about any file because it's just text.

Related

CSharp Windows Form Picturebox Draw Small Image Without Quality Loss

I'm trying to create a level editor using Windows Forms for my monogame project and need to draw small pixel based images to a picture box with no quality loss when scaled. In monogame when I need to do this I can just set the draw type to PointClamp and then each pixel is drawn as is instead of being pixelated when zoomed; I was hoping for something like this via a picturebox. Right now it looks like this But I'd prefer a more crisp and clean image like this (The second is how it'll appear in monogame). I haven't uploaded any code for this, but just assume I grabbed an image from the filestream and used the bitmap constructor to scale it up (don't think that's relevent but I'll just put it out there).
Image croppedImage, image = tileMap.tileBox.Image;
var brush = new SolidBrush(Color.Black);
try { croppedImage = CropImage(image, tileMap.highlightedRect); } catch {
return; // If crop target is outside bounds of image then return
}
float scale = Math.Min(higlightedTileBox.Width / croppedImage.Width, higlightedTileBox.Height / image.Height);
var scaleWidth = (int)(higlightedTileBox.Width * scale);
var scaleHeight = (int)(higlightedTileBox.Height * scale);
try { higlightedTileBox.Image = new Bitmap(croppedImage, new Size(scaleWidth, scaleHeight)); } catch {
return; // Image couldn't be scaled or highlighted tileBox couldn't be set to desired image
}
CropImage:
private static Image CropImage(Bitmap img, Rectangle cropArea) {
return img.Clone(cropArea, img.PixelFormat);
}
private static Image CropImage(Image img, Rectangle cropArea) {
return CropImage(new Bitmap(img), cropArea);
}
The code above is my current method in it's entirety. tileMap is a form and tilebox is the picturebox within that form.image is the full spritesheet texture before being cropped to what the user has highlighted. After being cropped I attempt to set the current picturebox (highlightedTileBox's) image to a scaled up version of the cropped image.
So I got a solution by trying around a bit.
It looks like scaling images directly by size is using some sort of interpolation.
To try different interpolation modes supported by Winforms, I created a little demo.
As you can see, every label contains the name of the InterpolationMode and is followed by its resulting image. The original bitmap I used is the small one at the top.
From your question, it looks like you would like to achieve something like NearestNeighbour.
Following code scales bmp and the result is stored in bmp2. Try if that's what you want. Consider building a proper implementation if you're using this as solution (disposing unused bitmaps etc.).
I hope it helps.
Bitmap bmp = new Bitmap("test.bmp");
Bitmap bmp2;
Graphics g = Graphics.FromImage(bmp2=new Bitmap(bmp.Width * 2, bmp.Height * 2));
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
g.DrawImage(bmp, 0, 0, bmp.Width * 2, bmp.Height * 2);
g.Dispose();

Clone a image to a larger one without resize using Magick.NET

I've searched a bit around the discussions\forums/StackOverflow/Official documentation, but i couldn't find much information about how to achieve what i'm trying. Most of the official documentation covers the command-line version of ImageMagick.
I'll describe what i'm trying to do:
I have a image loaded that i would like to paste into a larger one.
Ex: the image i loaded has 9920 width, 7085 height. I would like to place it in the middle of a larger one (10594 width, 7387 height). I do have all border calculation ready ([larger width - original width / 2] , same goes for height).
But i don't know how to do it using MagickImage. Here's the max i got:
private void drawInkzone(MagickImage loadedImage, List<string>inkzoneAreaInformation, string filePath)
{
unitConversion converter = new unitConversion();
List<double> inkZoneInfo = inkZoneListFill(inkzoneAreaInformation);
float DPI = getImageDPI(filePath);
double zoneAreaWidth_Pixels = converter.mmToPixel(inkZoneInfo.ElementAt(4), DPI);
double zoneAreaHeight_Pixels = converter.mmToPixel(inkZoneInfo.ElementAt(5), DPI);
using (MagickImage image = new MagickImage(MagickColor.FromRgb(255, 255, 255), Convert.ToInt32(zoneAreaWidth_Pixels), Convert.ToInt32(zoneAreaHeight_Pixels)))
{
//first: defining the larger image, with a white background (must be transparent, but for now its okay)
using (MagickImage original = loadedImage.Clone())
{
//Cloned the original image (already passed as parameter)
}
}
Here's the max i got. In order to achieve this, i used the following post:
How to process only one part of image by ImageMagick?
And i'm not using GDI+ because i'll be always working with larger TIFF files (big resolutions), and GDI+ tends to throw exceptions (Parameter not valid, out of memory) when it can't handle everything (i loaded three images with an resolution like that, and got out of memory).
Any help will be kindly appreciate, thanks.
Pablo.
You could either Composite the image on top of a new image with the required background or you could Clone and Extent if with the required background. In the answer from #Pablo Costa there is an example for Compositing the image so here is an example on how you could extent the image:
private void drawInkzone(MagickImage loadedImage, List<string> inkzoneAreaInformation, string filePath)
{
unitConversion converter = new unitConversion();
List<double> inkZoneInfo = inkZoneListFill(inkzoneAreaInformation);
float DPI = getImageDPI(filePath);
double zoneAreaWidth_Pixels = converter.mmToPixel(inkZoneInfo.ElementAt(4), DPI);
double zoneAreaHeight_Pixels = converter.mmToPixel(inkZoneInfo.ElementAt(5), DPI);
using (MagickImage image = loadedImage.Clone())
{
MagickColor background = MagickColors.Black;
int width = (int)zoneAreaWidth_Pixels;
int height = (int)zoneAreaHeight_Pixels;
image.Extent(width, height, Gravity.Center, background);
image.Write(#"C:\DI_PLOT\whatever.png");
}
}
I managed to accomplish what i needed.
Cool that i didn't had to calculate borders.
Here's the code:
private void drawInkzone(MagickImage loadedImage, List<string>inkzoneAreaInformation, string filePath)
{
unitConversion converter = new unitConversion();
List<double> inkZoneInfo = inkZoneListFill(inkzoneAreaInformation); //Larger image information
float DPI = getImageDPI(filePath);
double zoneAreaWidth_Pixels = converter.mmToPixel(inkZoneInfo.ElementAt(4), DPI); //Width and height for the larger image are in mm , converted them to pixel
double zoneAreaHeight_Pixels = converter.mmToPixel(inkZoneInfo.ElementAt(5), DPI);//Formula (is: mm * imageDPI) / 25.4
using (MagickImage image = new MagickImage(MagickColor.FromRgb(0, 0, 0), Convert.ToInt32(zoneAreaWidth_Pixels), Convert.ToInt32(zoneAreaHeight_Pixels)))
{
//first: defining the larger image, with a white background (must be transparent, but for now its okay)
using (MagickImage original = loadedImage.Clone())
{
//Cloned the original image (already passed as parameter)
image.Composite(loadedImage, Gravity.Center);
image.Write(#"C:\DI_PLOT\whatever.png");
}
}
Hope this helps someone :)

How can i add two animated gif's on one bitmap?

I have two animated gifs i created.
I want to add them to a new bitmap side by side so i will see both animated gifs animation.
Not as stil image but two animation side by side.
This code is in the top of form1 im using now:
public static class BitmapExtensions
{
public static Bitmap DoubleBitmap(this Bitmap bm)
{
Bitmap bitmap = new Bitmap(bm.Width * 2, bm.Height);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.DrawImage(bm, Point.Empty);
g.DrawImage(bm, new Point(bm.Width, 0));
return bitmap;
}
}
public static Bitmap AppendBitmap(this Bitmap bm, Bitmap rightBitmap)
{
Bitmap bitmap = new Bitmap(bm.Width + rightBitmap.Width, Math.Max(bm.Height, rightBitmap.Height));
using (Graphics g = Graphics.FromImage(bitmap))
{
g.DrawImage(bm, Point.Empty);
g.DrawImage(rightBitmap, new Point(bm.Width, 0));
return bitmap;
}
}
}
Then i use it like this:
private void CreateNewImage(string DirOfUrls)
{
List<string> files = Directory.GetFiles(DirOfUrls, "RainImage*.*").ToList();
List<string> files1 = Directory.GetFiles(DirOfUrls, "SatelliteImage*.*").ToList();
Bitmap bmp = new Bitmap(#"d:\localpath\RainMapGif");//files1[i]);
Bitmap bmp1 = new Bitmap(#"d:\localpath\SatelliteMapGif");//files[i]);
//Use it
//Double the same image
Bitmap doubledBitmap = bmp1.DoubleBitmap();
//Append new image
Bitmap appendedBitmap = bmp1.AppendBitmap(bmp);
appendedBitmap.Save(#"d:\localpath\newbitmapGif", System.Drawing.Imaging.ImageFormat.Gif);
}
RainMapGif and SatelliteMapGif are animated gif's.
But when i tried to do it this way i get one new bitmap with two stills images and not two animtions of the two animated gifs.
How can i add both animated gifs to one bitmap and when i open the bitmap on internet explorer for example i will see both animations moving of the two gifs side by side ?
EDIT**
This is how i used it before :
private void CreateNewImage(string DirOfUrls)
{
int newImageCounter = 0;
List<string> files = Directory.GetFiles(DirOfUrls, "RainImage*.*").ToList();
List<string> files1 = Directory.GetFiles(DirOfUrls, "SatelliteImage*.*").ToList();
for (int i = 0; i < files.Count; i++)
{
if (newImageCounter == 9)
{
CreateNewGif(DirOfUrls);
//break;
}
Bitmap bmp = new Bitmap(files1[i]);
Bitmap bmp1 = new Bitmap(files[i]);
//Use it
//Double the same image
Bitmap doubledBitmap = bmp1.DoubleBitmap();
//Append new image
Bitmap appendedBitmap = bmp1.AppendBitmap(bmp);
appendedBitmap.Save(#"d:\localpath\newbitmap" + newImageCounter.ToString("D6"), System.Drawing.Imaging.ImageFormat.Gif);
newImageCounter++;
}
So i have 9 images of both of them the RainMap images and the SatelliteMap images.
And the rest of the SatelliteMap images are singles.
Then im using CreateNewGif:
private void CreateNewGif(string urlsdirs)
{
List<string> files = Directory.GetFiles(urlsdirs, "RainImage*.*").ToList();
List<string> files1 = Directory.GetFiles(urlsdirs, "SatelliteImage*.*").ToList();
List<string> test = files;
test.RemoveRange(0, files1.Count);
List<string> newbitmap = Directory.GetFiles(localdir, "newbitmap*.*").ToList();
for (int i = 0; i < test.Count; i++)
{
newbitmap.Add(test[i]);
}
uf.MakeGIF(newbitmap, localdir + "newbitmapGif", 50, true);
}
And make new animated gif:
uf.MakeGIF(newbitmap, localdir + "newbitmapGif", 50, true);
But the new animated gif is not good since the rain images ending before the satellite images so the new animated gif show both animation and after 9 frames only one is continue.
How can i make that the one with the 9 images will keep continue animated over and over again and the second one will keep animated untill the end ?
This is the problem veljkoz wrote about before. One animation count is shorter then the other one. But how can i solve it ?
Only gif can have animation. Bitmap doesn't and never will.
Furthermore, there's the issue of extracting all of the gif slides (see this answer), putting them side by side in another gif (see this answer), and deciding what will you do if the slide count isn't a match (which would most probably be the case).
Personally, I would go with what #Mike W is suggesting in the comment...
Edit:
You have to have in mind that the resulting gif will have a single number of frames after which it repeats itself. So, both gifs you're trying to add have to somehow fit there. There's only a few options here:
Repeat inserting all frames of both gifs until they reach at the end at the same time (e.g. if one has 6 frames and the other 9 - the result will have 18 frames. The the first one would repeat itself 3 times, the other 2). This is (obviously) prolonging the length & size of the gif, which is probably not something you want, but it would give you best results. When the numbers are prime numbers you'd get the worst count - e.g. 53 & 59 frame gifs when joined will last for 3127 frames.
Change the timing of the frames so they end at the same time. This would of course speed-up / slow down parts of the gifs. (e.g. 6&9 frames gifs: the result has 9 slides - you could repeat the first 3 slides of 1st gif to last two frames - which means 1st slide will last 2 frames (#1 & #2), second one also (#3 & #4) as well as third (#5 & #6). Then copy the rest of the slides - frame 4 displayed at #7, 5->#8, 6->#9 and that's the end).
Remove some of the slides - shorten the gifs by removing some of the slides so the count matches...

Graphics DrawImage causes error with big red X

I have a collection of bitmap images that I am looping through and writing them all to one new bitmap. Basically I am taking a loose collection of bitmaps and writing them all to one bitmap one after another so that they are visible as one image.
When i call dc.DrawImage from one of the bitmaps in the collection onto the new bitmap my winform is showing a big red X in the form. When I set a PictureBox.Image to the newly drawn bitmap I am getting a big red X.
For some reason i cannot find the error anywhere. I am not able to locate the error with debugging.
Now, if I just set the PictureBox.Image to one of the images in the collection of images with-out looping and drawning onto a new bitmap everything works fine.
To make everything ease I am only working with one bitmap that is in the collection and drawing the one bitmap to the new bitmap. So I know I have only one bitmap to get working then i can add the other ones.
In the images below is what the form looks like if i just set the picturebox.image of the image in the collection.
The second image is the error that shows after I loop and drawing the bitmap in the collection to another bitmap.
The code below is what needs to work, but throws an error.
Notice where I am setting the property of the PictureBox.Image like so:
this.picBx.Image = schedule; this causes the error.
But if i set the picturebox.image like so:
this.picBx.Image = schedules[0].Door; it works just fine.
DoorSchedules schedules = GetDoorDrawing(elev, projInfo.ProjectName);
int prevWidth = 0;
//
using (Bitmap schedule = new Bitmap(schedules.Width + 50, schedules.Height + 50))
{
using (Graphics dc = Graphics.FromImage(schedule))
{
using (Pen pen = new Pen(LINE_COLOR))
{
pen.Width = 4;
pen.Color =
Color.FromArgb(50, LINE_COLOR.R, LINE_COLOR.G, LINE_COLOR.B);
//
for (byte i = 0; i < schedules.Count; i++)
{
if (i > 0)
{
dc.DrawLine(pen, prevWidth - 25, 0,
prevWidth - 25, schedule.Height);
};
dc.DrawImage(schedules[i].Door, prevWidth, 0);
prevWidth += schedules[i].Door.Width;
};
};
};
this.picBx.Image = schedule;
this.picBx.BackColor = BACK_COLOR;
this.Size = new System.Drawing.Size(schedule.Width, schedule.Height);
};
You have Bitmap schedule defined in a using statement.
When that using block ends, the bitmap is disposed.

Resize Image of any size to fixed dimension using C# ASP.Net web form

I have done image resizing while allowing user to upload a specific size image and then crop them to different dimension i have also used jCrop in project to allow users to upload a image of specific size and then select the image area & crop it accordingly.
In new project i have a requirement where user can upload any size image which is at least larger than 500Px in width and then i have to allow user to select the part of image using jCrop and then save image in different dimension of 475x313 , 310x205 while maintaining the aspect ration.
I can do it with if i allow the used to upload a fixed size image but i am not sure how i can handle variable size image.
I also need to display the image uploaded before cropping in a fixed size box.. let us say 300x200. in this area i have to allow the user to select the part of the image before i can crop.
Issue i am facing is how to handle variable length image and show it is a fixed image box of 300x200px.
I wrote an article on using jCrop with dynamically-resized uploaded images, which seems to be what you're needing.
If you're looking for an open-source ASP.NET control that does it for you, check out cropimage.net.
Want to going to by programmatically than you can try this :
if you are using file upload for upload images
string path = Path.GetFileName(fileuploaderID.PostedFile.FileName);
ConvertThumbnails(width, height, fileuploaderID.FileBytes, path);
your function
public void ConvertThumbnails(int width, int height, byte[] filestream, string path)
{
// create an image object, using the filename we just retrieved
var stream = new MemoryStream(filestream);
System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
try
{
int fullSizeImgWidth = image.Width;
int fullSizeImgHeight = image.Height;
float imgWidth = 0.0F;
float imgHeight = 0.0F;
imgWidth = width;
imgHeight = height;
Bitmap thumbNailImg = new Bitmap(image, (int)imgWidth, (int)imgHeight);
MemoryStream ms = new MemoryStream();
// Save to memory using the Jpeg format
thumbNailImg.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
// read to end
byte[] bmpBytes = ms.GetBuffer();
item.Attachments.Add(path, bmpBytes);
thumbNailImg.Dispose();
ms.Close();
}
catch (Exception)
{
image.Dispose();
}
}

Categories

Resources