I have a resource file contain a PNG file I want to write byte array to the End Of File PNG image but when saving the file from stream remove byte array, I want to write hidden bytes to PNG file, How to resolve this issue?
public void Method()
{
using (var reader = new ResourceReader("My.resource"))
{
var iter = reader.GetEnumerator();
var ms = new MemoryStream();
var writer = new System.Resources.ResourceWriter(ms);
while (iter.MoveNext())
{
var key = iter.Key as string;
var value = iter.Value as Bitmap;
MemoryStream stream = new MemoryStream();
value.Save(stream, value.RawFormat);
byte[] b = new byte[] {0x11, 0x22, 0x33};
stream.Write(b, 0, b.Length);
Image bitmap = Image.FromStream(stream);
writer.AddResource(key, bitmap);
}
writer.Generate();
File.WriteAllBytes("My1.resource", ms.ToArray());
}
}
Related
Hi am trying to get bitmap to display from DICOM file , but when try to create bitmap from the buffer I get Parameter is not valid for the Bitmap constructor call. I use the following code
gdcm.ImageReader reader = new gdcm.ImageReader();
reader.SetFileName(_dicomFilePath);
if (reader.Read())
{
var image = reader.GetImage();
if (image != null)
{
byte[] imageByteArray = new byte[image.GetBufferLength()];
if (image.GetBuffer(imageByteArray))
{
MemoryStream stream = new MemoryStream();
stream.Write(imageByteArray, 0, imageByteArray.Length);
stream.Seek(0, SeekOrigin.Begin);
Bitmap bmp = new Bitmap(stream);
CurrentFrameDataGDCM = Imaging.CreateBitmapSourceFromHBitmap(
bmp.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromWidthAndHeight((int)image.GetRows(), (int)image.GetColumns()));
}
}
}
I'm using the C# System.IO class (framework 4.0) to compress an image pulled off the file system with FileDialog and then inserted into a SQL Server database as a varbinary(max) data type. The problem I'm having is when I pull the data out of the database and attempt to decompress I get the subject error with an additional message -- make sure you are passing in a gzip stream.
The code to get the file:
OpenFileDialog dlgOpen = new OpenFileDialog();
if (dlgOpen.ShowDialog() == DialogResult.OK)
{
FileStream fs = File.OpenRead(dlgOpen.FileName);
byte[] picbyte1 = new byte[fs.Length];
byte[] picbyte = Compress(picbyte1);
fs.Read(picbyte, 0, System.Convert.ToInt32(picbyte.Length));
String ImageName = dlgOpen.FileName;
//String bs64OfBytes = Convert.ToBase64String(picbyte);
fs.Close();
//additional code inserts into database
....
}
The compress method:
private static byte[] Compress(byte[] data)
{
var output = new MemoryStream();
using (var gzip = new GZipStream(output, CompressionMode.Compress, true))
{
gzip.Write(data, 0, data.Length);
gzip.Close();
}
return output.ToArray();
}
The decompress method:
private static byte[] Decompress(byte[] data)
{
var output = new MemoryStream();
var input = new MemoryStream();
input.Write(data, 0, data.Length);
input.Position = 0;
using (var gzip = new GZipStream(input, CompressionMode.Decompress, true))
{
var buff = new byte[64];//also used 32
var read = gzip.Read(buff, 0, buff.Length);//error occurs here
while (read > 0)
{
output.Write(buff, 0, read);
read = gzip.Read(buff, 0, buff.Length);
}
gzip.Close();
}
return output.ToArray();
}
You need to insert a line and remove an other:
FileStream fs = File.OpenRead(dlgOpen.FileName);
byte[] picbyte1 = new byte[fs.Length];
fs.Read(picbyte1, 0, (int)fs.Length); // <-- Add this one
byte[] picbyte = Compress(picbyte1);
// fs.Read(picbyte, 0, System.Convert.ToInt32(picbyte.Length)); // <-- And remove this one
// ...
You are reading the image in your code, but something is in the wrong order:
// Original but incorrect sequence
FileStream fs = File.OpenRead(dlgOpen.FileName); // Open the file
byte[] picbyte1 = new byte[fs.Length]; // Assign the array
byte[] picbyte = Compress(picbyte1); // Compress the assigned array, but there is no contents...
fs.Read(picbyte, 0, System.Convert.ToInt32(picbyte.Length)); // You save the file to the already compressed bytes...
So you have saved the first part of the original file, not the compressed one (but the number of saved bytes corresponds with the number of compressed bytes). If you send this to the DB and read it back, the decompressor does not find it's Magic Number.
As an improvement, you can change these lines:
FileStream fs = File.OpenRead(dlgOpen.FileName);
byte[] picbyte1 = new byte[fs.Length];
fs.Read(picbyte1, 0, (int)fs.Length); // line that I suggested to add
probably change to:
byte[] picbyte1 = File.ReadAllBytes(dlgOpen.FileName);
I am trying to convert a Base64String to an image which needs to be saved locally.
At the moment, my code is able to save the image but when I open the saved image, it says "Invalid Image".
Code:
try
{
using (var imageFile = new StreamWriter(filePath))
{
imageFile.Write(resizeImage.Content);
imageFile.Close();
}
}
The Content is a string object which contains the Base64 String.
First, convert the base 64 string to an Image, then use the Image.Save method.
To convert from base 64 string to Image:
public Image Base64ToImage(string base64String)
{
// Convert base 64 string to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
// Convert byte[] to Image
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
Image image = Image.FromStream(ms, true);
return image;
}
}
To convert from Image to base 64 string:
public string ImageToBase64(Image image,System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to base 64 string
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
Finally, you can easily to call Image.Save(filePath); to save the image.
So with the code you have provided.
var bytes = Convert.FromBase64String(resizeImage.Content);
using (var imageFile = new FileStream(filePath, FileMode.Create))
{
imageFile.Write(bytes ,0, bytes.Length);
imageFile.Flush();
}
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
Front :
<Image Name="camImage"/>
Back:
public async void Base64ToImage(string base64String)
{
// read stream
var bytes = Convert.FromBase64String(base64String);
var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();
// decode image
var decoder = await BitmapDecoder.CreateAsync(image);
image.Seek(0);
// create bitmap
var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
await output.SetSourceAsync(image);
camImage.Source = output;
}
So, I have the function, which gets BitmapImage, I need to save it to iso storage and convert to Base64 (for sending to server). However, copying from fileStream to memoryStream is not successful.
public void SetImage(BitmapImage bitmap)
{
if (isoFiles.FileExists(Settings.FILE_AVATAR_JPG))
isoFiles.DeleteFile(Settings.FILE_AVATAR_JPG);
var fileStream = isoFiles.CreateFile(Settings.FILE_AVATAR_JPG);
var wb = new WriteableBitmap(bitmap);
wb.SaveJpeg(fileStream, 120, 120, 0, 85); // file is saved
var memoryStream = new MemoryStream();
fileStream.CopyTo(memoryStream); // here, memoryStream is null
byte[] result = memoryStream.ToArray();
fileStream.Close();
var base64 = Convert.ToBase64String(result);
}
Stream.CopyTo copies from the current position of fileStream which has been changed by SaveJpeg() so you need to reset it;
var memoryStream = new MemoryStream();
fileStream.Position = 0;
fileStream.CopyTo(memoryStream);
I'm working on file manager project. I need to generate thumbnail if file is of image type. i'm able to get by using IHttpHandler with method
Sytem.Drawing.Image.GetThumbnailImage(),
Here is some code
Hashtable ht;
ht = new Hashtable();
using (FileStream fInfo = new FileStream(context.Server.MapPath(url), FileMode.Open))
{
byte[] bFile;
bFile = GenerateThumbnail(fInfo, XLen, YLen);
ht.Add(id, bFile);
fInfo.Close();
Byte[] arrImg = (byte[])ht[id];
context.Response.Clear();
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(arrImg);
context.Response.End();
}
private byte[] GenerateThumbnail(Stream fStream, string xLen, string yLen)
{
using (Image img = Image.FromStream(fStream))
{
Image thumbnailImage = img.GetThumbnailImage(int.Parse(xLen), int.Parse(yLen), new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
using (MemoryStream imageStream = new MemoryStream())
{
thumbnailImage.Save(imageStream,System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageContent = new Byte[imageStream.Length];
imageStream.Position = 0;
imageStream.Read(imageContent, 0, (int)imageStream.Length);
return imageContent;
}
}
}
Problem
Newly uploaded file on genrating thumb throwing expection : being used by another process, after sometime its shows the thumbnail. Q. where im missing to close the stream ?