Convert Tiff memory stream to Bitmap - c#

I'm working on a Outlook add-in that's converts attachments. When trying to convert an Tiff attachment to a Bitmap I get:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException. Oveloaded method System.Windows.Media.Imaging.TiffBitmapDecoder.TiffBitmapDecoder has invallid arguments.
The code:
const string PR_ATTACH_DATA_BIN = "http://schemas.microsoft.com/mapi/proptag/0x37010102";
// Retrieve the attachment as a byte array
var attachmentData = myOutlookAttachement.PropertyAccessor.GetProperty(PR_ATTACH_DATA_BIN);
TiffBitmapDecoder decoder = new TiffBitmapDecoder(attachmentData, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];
Bitmap bmp = new Bitmap(bitmapSource.PixelWidth, bitmapSource.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

Thanks to Alex K I found the answer:
const string PR_ATTACH_DATA_BIN = "http://schemas.microsoft.com/mapi/proptag/0x37010102";
// Retrieve the attachment as a byte array
var attachmentData = myOutlookAttachement.PropertyAccessor.GetProperty(PR_ATTACH_DATA_BIN);
Stream stream = new MemoryStream(attachmentData);
TiffBitmapDecoder decoder = new TiffBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];
Bitmap bmp = new Bitmap(bitmapSource.PixelWidth, bitmapSource.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

Related

get Image from ImageView and convert it to Bitmap of system.Drawing

I want to convert Image in ImageView to bitmap Of System.Drawing to use in code
or function It accept Bitmap of system.Drawing not bitmap of Android.Graphics.
I guess you want to use the Source of ImageView as like the Bitmap
Suppose:
Source of ImageView is filepath1, where the filepath1 is a file path string standing for a jpg file.
Then you can try the following code:
if (file != null)
{
byte[] imageBytes;
var FileImage = new Image();
string base64;
using (var fs = new FileStream(file.FilePath, FileMode.Open, FileAccess.Read))
{
var buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
base64 = Convert.ToBase64String(buffer);
}
imageBytes = Convert.FromBase64String(base64);
File.WriteAllBytes(filename, imageBytes);
var bitmap = new Image { Source = filename};
imgViewer2.Source = bitmap.Source;

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);
}
}

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);

Converting FileStream to WriteableBitmap to JPEG to Byte Array for SSRS

I'm trying to save an Image to SQL Server so SSRS can read it. I need to convert to WriteableBitmap (and possibly JPEG?) so I can make changes to the image size before saving. However, when I try to pull the converted image out of SQL Server, it will not render in SSRS at all. What am I doing wrong?
byte[] m_Bytes = ReadToEnd(fileStream); //this works fine
WriteableBitmap bmp1 = new WriteableBitmap(166, 166);
bmp1.FromByteArray(m_Bytes); //this works fine
ExtendedImage image = bmp1.ToImage();
MemoryStream stream = new MemoryStream();
ImageTools.IO.Encoders.AddEncoder<JpegEncoder>();
JpegEncoder encoder = new JpegEncoder();
encoder.Encode(image, stream);
BitmapImage img = new BitmapImage();
img.SetSource(stream);
WriteableBitmap bmp2 = new WriteableBitmap(img);
byte[] buffer1 = bmp2.ToByteArray();
CurrentOrder.CompanyImage = buffer1; //this does save a byte array but it will not render in SSRS. If I set buffer1 to bmp1.ToByteArray() then it works fine but I am still unable to resize it using the resize method in WriteableEx without it not rendering in SSRS.
This is another try at the same thing and it won't render either:
And this is simpler and won't work either:
byte[] m_Bytes = ReadToEnd(fileStream);
WriteableBitmap bmp1 = new WriteableBitmap(166, 166);
bmp1.FromByteArray(m_Bytes);
WriteableBitmap resizedImage = bmp1.Resize(25, 25, WriteableBitmapExtensions.Interpolation.Bilinear);
byte[] buffer1 = resizedImage.ToByteArray();
CurrentOrder.CompanyImage = buffer1;
What you want is to resize 166x166 (or 25x25), export as byte[] and reload picture from this byte array ?
Can you try with BitmapImage ?
BitmapImage image = new BitmapImage();
image.SetSource(fileStream);
WriteableBitmap bitmap = new WriteableBitmap(image);
WriteableBitmap resizedBitmap = bitmap.Resize(25, 25, WriteableBitmapExtensions.Interpolation.Bilinear);
CurrentOrder.CompanyImage = resizedBitmap.ToByteArray();

How to put image in a picture box from a byte[] in C#

I've a byte array which contains an image binary data in bitmap format. How do I display it using the PictureBox control in C#?
I went thru a couple of posts listed below but not sure if I need to convert the byte array into something else before sending it to a picturebox. I'd appreciate your help. Thanks!
How to put image in a picture box from Bitmap
Load Picturebox Image From Memory?
This function converts byte array into Bitmap which can be use to set the Image Property of the picturebox.
public static Bitmap ByteToImage(byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
return bm;
}
Sample usage:
pictureBox.Image = ByteToImage(byteArr); // byteArr holds byte array value
byte[] imageSource = **byte array**;
Bitmap image;
using (MemoryStream stream = new MemoryStream(imageSource))
{
image = new Bitmap(stream);
}
pictureBox.Image = image;
using System.IO;
byte[] img = File.ReadAllBytes(openFileDialog1.FileName);
MemoryStream ms = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(ms);
or you can access like this directly,
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
You can also convert pictureBox image to byte array like this,
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] img = ms.ToArray();
The ImageConverter class in the System.Drawing namespace can do the conversion:
byte[] imageArray = **byte array**
ImageConverter converter = new ImageConverter();
pictureButton.Image = (Image)converter.ConvertFrom(imageArray);
If you want to use BinaryReader to convert then use like this,
FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] img = br.ReadBytes((int)fs.Length);
Try this for Converting Bitmap Images to array of bytes for jpeg pictures and png file types:
public byte[] UdfConvertPicToByte(Bitmap bitmapImages)
{
using (MemoryStream stream = new MemoryStream())
{
bitmapImages.Compress(Bitmap.CompressFormat.Png, 0, stream);
byte[] bitmapData = stream.ToArray();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 50, stream);
bitmapData = stream.ToArray();
return bitmapData;
}
}

Categories

Resources