MemoryTributary GetBuffer - c#

My application is MVC5 C#, I use memorystream to generate images using the following:
using (var memStream = new MemoryStream())
{
const int quality = 90;
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, (long)quality);
objImage.Save(memStream, GetImageCodeInfo("image/png"), encoderParameters);
data = this.File(memStream.GetBuffer(), "image/png");
memStream.Dispose();
}
However I get OutOfMemoryException with some files. I was reading about MemoryTributary but could not find a solution to GetBuffer! Would appreciate your suggestions.

How about leaving all the buffer stuff out?
var memStream = new MemoryStream();
const int quality = 90;
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, (long)quality);
objImage.Save(memStream, GetImageCodeInfo("image/png"), encoderParameters);
memStream.Seek(0, SeekOrigin.Begin);
return File(memStream, "image/png");
The FileStreamResult will dispose the MemoryStream, no need to worry about that.

Related

C# how to compress .png without transparent background lost?

I use the following codes to compress an image file to jpg:
// _rawBitmap = a Bitmap object
ImageCodecInfo encoder = GetEncoder(ImageFormat.Jpeg);
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
myEncoderParameters.Param[0] = myEncoderParameter;
ImageConverter imageConverter = new ImageConverter();
byte[] b = (byte[])imageConverter.ConvertTo(_rawBitmap, typeof(byte[]));
using (MemoryStream ms = new MemoryStream())
{
ms.Write(b, 0, b.Length);
ms.Seek(0, SeekOrigin.Begin);
rawBitmap.Save(ms, encoder, myEncoderParameters);
bmp = ToBitmap(ms.ToArray());
return (Bitmap)bmp.Clone();
}
but when I try to compress a png file with same way but only change:
ImageCodecInfo encoder = GetEncoder(ImageFormat.Jpeg);
to
ImageCodecInfo encoder = GetEncoder(ImageFormat.Png);
my png file lost transparent data.
so how to compress a PNG file properly?
There are a couple of problems here.
First, you don't need to set those EncoderParams for quality for PNG.
Second, you don't need ImageConverter
Third, you are writing whatever ImageConverter produces to your memory stream, rewinding, and then writing the encoded PNG over the top of it-- it is likely that you have a PNG file with a bunch of garbage at the end of it as a result.
The simplified approach should be:
using (MemoryStream ms = new MemoryStream())
{
rawBitmap.Save(ms, ImageFormat.Png);
}
If you want to load your bitmap back, open it from the stream, but don't close the stream (the stream will be disposed when your returned Bitmap is disposed):
var ms = new MemoryStream();
rawBitmap.Save(ms, ImageFormat.Png);
ms.Seek(0, SeekOrigin.Begin);
return Bitmap.FromStream(ms);
You can use nQuant (https://www.nuget.org/packages/nQuant/)
With it, you convert 32 bit PNGs to high quality 8 bit PNGs
private static int alphaTransparency = 10;
private static int alphaFader = 70;
var quantizer = new WuQuantizer();
using(var bitmap = new Bitmap(sourcePath))
{
using(var quantized = quantizer.QuantizeImage(bitmap, alphaTransparency, alphaFader))
{
quantized.Save(targetPath, ImageFormat.Png);
}
}

Dispalying pictures from database in xaml

I write image in local database.
MemoryStream stream = new MemoryStream();
WriteableBitmap mywbq = new WriteableBitmap(bmp);
mywbq.SaveJpeg(stream, mywbq.PixelWidth, mywbq.PixelHeight, 0, 95);
byte[] imagearray = stream.ToArray();
stream.Close();
db._contacts.InsertOnSubmit(new MyContactsList {ItemImage = imagearray });
db.SubmitChanges();
And I want this picture display in xaml.
How it's impossible?
I use it source
But this class doesn't work
Simple as that:
byte[] yourImageBytesFromDatabase = ......;
MemoryStream ms = new MemoryStream();
ms.Write(yourImageBytesFromDatabase, 0, yourImageBytesFromDatabase.Length);
BitmapImage src = new BitmapImage();
src.SetSource(ms);

Convert bitmap to ImageSource give NullReference exception

I've got WCF service to send image as a stream to client app.
My client app gets the stream :
Stream imageStream = client.GetImage();
When I use this code:
imageStream.CopyTo(stream);
int size = (int)stream.Length;
stream.Seek(0, SeekOrigin.Begin);
BitmapFrame bf = BitmapFrame.Create(stream,
BitmapCreateOptions.None,
BitmapCacheOption.OnLoad);
cam_img.Source = bf;
It work's fine but I need apply some filters to image before assign to source.
So I need bitmap. First, I convert Stream imageStream to byte array and then I use some code I find on forums:
byte[] tab_img;
using (var memoryStream = new MemoryStream())
{
imageStream.CopyTo(memoryStream);
tab_img= memoryStream.ToArray();
}
Bitmap bm;
using (MemoryStream mStream = new MemoryStream())
{
mStream.Write (tab_img, 0, tab_img.Length);
mStream.Seek(0, SeekOrigin.Begin);
bm = new Bitmap(mStream);
Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
Bitmap bm_post = filter.Apply(bm);
ImageSourceConverter c = new ImageSourceConverter();
object source = new ImageSourceConverter().ConvertFrom(bm_post);
ImageSource is1 = (ImageSource)source;
cam_img.Source = is1;
}
but I still get NullReferenceException in line
object source = new ImageSourceConverter().ConvertFrom(bm_post);

Merging multiple TIF files in C#

I am trying to combine multiple .tif files into one, but after merging, the new .tif file's image quality is very low.
How to increase that quality?
I want the new merged file quality as original quality. I am using this code to merged the tif file
string[] sa = path;
ImageCodecInfo info = null;
foreach (ImageCodecInfo ice in ImageCodecInfo.GetImageEncoders())
if (ice.MimeType == "image/tiff")
info = ice;
Encoder enc = Encoder.SaveFlag;
EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
Bitmap pages = null;
int frame = 0;
foreach (string s in sa)
{
// using (FileStream fileStream = System.IO.File.Open(s, FileMode.Open))
{
if (frame == 0)
{
pages = (Bitmap)Image.FromFile(s);
//save the first frame
pages.Save(filepath, info, ep);
}
else
{
//save the intermediate frames
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);
Bitmap bm = (Bitmap)Image.FromFile(s);
pages.SaveAdd(bm, ep);
}
if (frame == sa.Length - 1)
{
//flush and close.
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
pages.SaveAdd(ep);
}
frame++;
}
}
Not 100% sure about this one, but I believe Multi-Frame TIFFs are encoded using G3 by default. Just giving something to try, change this:
Encoder enc = Encoder.SaveFlag;
EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
to this:
Encoder enc = Encoder.SaveFlag;
Encoder encComp = Encoder.Encoder.Compression;
EncoderParameters ep = new EncoderParameters(2);
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
ep.Param[1] = new EncoderParameter(encComp, (long)EncoderValue.CompressionLZW);
And try again (you could also use CompressionNone instead of CompressionLZW, but LZW is lossless so it should not reduce the quality)

Change TIFF palette from 8 bit into 32 bit

I have some set of TIFF files (8-bit palette). I need to change the bit depth into 32 bit.
I tried the code below, but getting an error, that the parameter is not correct... Could you help me to fix it? Or maybe some1 is able to suggest some different solution for my problem.
public static class TiffConverter
{
public static void Convert8To32Bit(string fileName)
{
BitmapSource bitmapSource;
using (Stream imageStreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
bitmapSource = decoder.Frames[0];
}
using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate))
{
ImageCodecInfo tiffCodec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(codec => codec.FormatID.Equals(ImageFormat.Tiff.Guid));
if (tiffCodec != null)
{
Image image = BitmapFromSource(bitmapSource);
EncoderParameters parameters = new EncoderParameters();
parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 32);
image.Save(stream, tiffCodec, parameters);
}
}
}
private static Bitmap BitmapFromSource(BitmapSource bitmapSource)
{
Bitmap bitmap;
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapSource));
enc.Save(outStream);
bitmap = new Bitmap(outStream);
}
return bitmap;
}
}
Thanks in advance!
[edit]
I noticed that the error appears in this line:
image.Save(stream, tiffCodec, parameters);
ArgumentException occured: Parameter is not valid.
If the error you're getting is on the line:
parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 32);
then the problem is that the compiler cannot know if you're referring System.Text.Encoder or System.Drawing.Imaging.Encoder...
Your code should look like this to to avoid any ambiguity:
parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 32);
Edit:
This is an alternative (and tested :)) way of doing the same thing:
Image inputImg = Image.FromFile("input.tif");
var outputImg = new Bitmap(inputImg.Width, inputImg.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (var gr = Graphics.FromImage(outputImg))
gr.DrawImage(inputImg, new Rectangle(0, 0, inputImg.Width, inputImg.Height));
outputImg.Save("output.tif", ImageFormat.Tiff);

Categories

Resources