Ok now, the current code i am using
{
using (fs = new FileStream("test", FileMode.Create))
{
byte[] b = new byte[iLength + 1];
int y1 = 0;
axCZKEM1.GetPhotoByName(MachineNo, photoPath + ".jpg", out b[0], out y1);
btImage = b;
if (btImage != null)
{
fs.Write(btImage, 0, btImage.Length);
}
if (fs.Length > 0)
{
bmp1 = new Bitmap(fs);
bmp1.Save(ImgPath + photoPath + ".jpg");
Console.WriteLine(photoPath);
// fs = null;
bmp1 = new Bitmap(fs);
When i use the above code in backgroundworker or in thread ( bmp1 = new Bitmap(fs); ) this line is throwing Parameter is not valid exception , if somebody can help me out on this please.
Related
In the code I wrote for a telegram bot I wanted to place this code:
Telegram.Bot.Args.MessageEventArgs a
in the
Task.Run(() => { //code });
Because in the code I use a.Messages.From.Username and sometimes more than one user is using the bot and because of that I need to separate a.Messages.From.Username's, but I couldn't find any way.
This is my code:
void bot_OnMessage1(object sender, Telegram.Bot.Args.MessageEventArgs a)
{
Task.Run(() =>
{
string watermarkText = a.Message.Text;
string fileName = "C:\\temp\\01.png";
using (Bitmap bmp = new Bitmap(fileName))
{
using (Graphics grp = Graphics.FromImage(bmp))
{
bmp.Save("c:\\temp\\" + a.Message.From.Username + ".png", ImageFormat.Png);
using (FileStream fs = new FileStream("c:\\temp\\" + a.Message.From.Username + ".png", FileMode.Open))
{
fs.CanTimeout.ToString();
FileToSend fileToSend = new FileToSend("c:\\temp\\" + a.Message.From.Username + ".png", fs);
var rep = bot.SendPhotoAsync(a.Message.From.Id, fileToSend, "این عکس را پست کنید").Result;
}
}
}
});
}
I am trying to create a zip file that contains zip files inside of it. I am using ICSharpCode.SharpZipLib (must use this due to project restrictions). this works fine if I have only 1 byte[] array.. but it is not working for list of byte[].
foreach (byte[] internalZipFile in zipFiles)
{
// Source : internal zip file
MemoryStream inputMemoryStream = new MemoryStream(internalZipFile);
ZipEntry newZipEntry = new ZipEntry("AdManifest-" + i.ToString() + ".zip");
newZipEntry.DateTime = DateTime.Now;
zipStream.PutNextEntry(newZipEntry);
StreamUtils.Copy(inputMemoryStream, zipStream, new byte[1024]);
zipStream.CloseEntry();
zipStream.IsStreamOwner = false; // to stop the close and underlying stream
zipStream.Close();
outputMemoryStream.Position = 0;
zipByteArray = outputMemoryStream.ToArray();
i++;
}
using (FileStream fileStream = new FileStream(#"c:\manifest.zip", FileMode.Create))
{
fileStream.Write(zipByteArray, 0, zipByteArray.Length);
}
Can someone please assist? what am i missing?
I figured this out.
here us the one working for me :
byte[] zipByteArray = null;
int i = 0;
if (zipFiles != null && zipFiles.Count > 0)
{
MemoryStream outputMemoryStream = new MemoryStream();
ZipOutputStream zipStream = new ZipOutputStream(outputMemoryStream);
zipStream.SetLevel(3);
foreach (byte[] internalZipFile in zipFiles)
{
MemoryStream inputMemoryStream = new MemoryStream(internalZipFile);
ZipEntry newZipEntry = new ZipEntry("AdManifest-" + i.ToString() + ".zip");
newZipEntry.DateTime = DateTime.Now;
newZipEntry.Size = internalZipFile.Length;
zipStream.PutNextEntry(newZipEntry);
StreamUtils.Copy(inputMemoryStream, zipStream, new byte[1024]);
zipStream.CloseEntry();
i++;
}
zipStream.IsStreamOwner = false; // to stop the close and underlying stream
zipStream.Close();
outputMemoryStream.Position = 0;
zipByteArray = outputMemoryStream.ToArray();
using (FileStream fileStream = new FileStream(#"c:\manifest.zip", FileMode.Create))
{
fileStream.Write(zipByteArray, 0, zipByteArray.Length);
}
}
I can't try it, but i think than you need less code in iteration body
Plus that i've removed outpustmemorystream and used only zipStream.
foreach (byte[] internalZipFile in zipFiles)
{
// Source : internal zip file
MemoryStream inputMemoryStream = new MemoryStream(internalZipFile);
ZipEntry newZipEntry = new ZipEntry("AdManifest-" + i.ToString() + ".zip");
newZipEntry.DateTime = DateTime.Now;
zipStream.PutNextEntry(newZipEntry);
StreamUtils.Copy(inputMemoryStream, zipStream, new byte[1024]);
zipStream.CloseEntry();
i++;
}
zipStream.IsStreamOwner = false; // to stop the close and underlying stream
zipStream.Position = 0;
zipByteArray = zipStream.ToArray();
zipStream.Close();
using (FileStream fileStream = new FileStream(#"c:\manifest.zip", FileMode.Create))
{
fileStream.Write(zipByteArray, 0, zipByteArray.Length);
}
I am using Lumia 640 for development.
I got an memory out of exception in windows phone 8.1 Silver Light Application.
I have tried to dispose stream, remove bitmap from memory but still facing this issues.
When collecting More than 5 Images using CameraCaptureTask it will throws "memory out of exception".
I am posing My Demo Code Here.
private void Button_Click(object sender, RoutedEventArgs e)
{
CameraCaptureTask cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Show();
cameraCaptureTask.Completed += new EventHandler<PhotoResult>(this.CameraCaptureTaskCompleted);
}
private async void CameraCaptureTaskCompleted(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
Debug.WriteLine("[ApplicationCurrentMemoryUsage](MB) : \n" + (DeviceStatus.ApplicationCurrentMemoryUsage / 1024 / 1024));
Image attachedImage = new Image();
Stream fileStream = e.ChosenPhoto;
string strFolderName = "Capture";
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
var fileName = Guid.NewGuid() + ".JPG";
if (!isf.DirectoryExists(strFolderName))
{
isf.CreateDirectory(strFolderName);
}
if (isf.FileExists(strFolderName + "\\" + fileName))
{
isf.DeleteFile(strFolderName + "\\" + fileName);
}
IsolatedStorageFileStream isfs = isf.CreateFile(strFolderName + "\\" + fileName);
int bytesRead = 0;
var bufferSize = Convert.ToInt32(fileStream.Length);
var fileBytes = new byte[fileStream.Length];
while ((bytesRead = await fileStream.ReadAsync(fileBytes, 0, bufferSize)) > 0)
{
isfs.Write(fileBytes, 0, bytesRead);
}
BitmapImage bitImage = new BitmapImage();
bitImage.SetSource(fileStream);
bitImage.DecodePixelType = DecodePixelType.Physical;
bitImage.CreateOptions = BitmapCreateOptions.BackgroundCreation;
bitImage.CreateOptions = BitmapCreateOptions.DelayCreation;
double dblRation = (double)bitImage.PixelWidth / bitImage.PixelHeight;
//if (bitImage.PixelWidth > bitImage.PixelHeight)
//{
// bitImage.DecodePixelWidth = 200;
// bitImage.DecodePixelHeight = 200 / (int)dblRation;
//}
//else
//{
// bitImage.DecodePixelHeight = 200;
// bitImage.DecodePixelWidth = (int)(200 * dblRation);
//}
attachedImage.Source = bitImage;
GC.Collect();
GC.WaitForPendingFinalizers();
fileStream.Flush();
fileStream.Dispose();
fileStream.Close();
bitImage = null;
fileStream = null;
fileBytes = null;
sp.Children.Add(attachedImage);
Debug.WriteLine("[ApplicationCurrentMemoryUsage](MB) : \n" + (DeviceStatus.ApplicationCurrentMemoryUsage / 1024 / 1024));
}
}
It is just demo code. When I pick first image it will rise from 8 MB to 37 MB usage.But in real application it will rise from 64 MB to 112 MB.
Please help me to sort it out.
I have seen many issues involving the GDI+ Generic Error, but I have not seen this particular matter raised before. We are consistently getting the error, on Windows systems other than Windows 8, when attempting to read (System.Drawing.Image.SelectActiveFrame) a multiple-frame tiff that includes frames in mixed Photometric Interpretation formats. That is to say, the file includes both RGB color and min-is-white formats, with corresponding differences in the Bits/Sample and Samples/Pixel frame parameters. The error is consistently raising as soon as a frame is encountered with a format that is different from that of the first frame.
// Convert File from .tiff to .PDF
static void ConvertFile(string file, string pdffilename)
{
string localMessage = string.Empty;
try
{
//if it's a PDF Just renamed it and continue
if (file.ToLower().Contains(".pdf"))
{
File.Copy(file, pdffilename);
return;
}
// If file exists return
if (File.Exists(pdffilename)) { return; }
using (var stream = new FileStream(pdffilename, FileMode.Create))
{
localMessage = "01";
var document = new iTextSharp.text.Document();
localMessage = "01";
var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream);
localMessage = "02";
var bm = Bitmap.FromFile(file);
localMessage = "03";
var total = bm.GetFrameCount(FrameDimension.Page);
localMessage = "04";
document.Open();
//iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
localMessage = "05";
iTextSharp.text.Image img = null;
for (var currentframe = 0; currentframe < total; ++currentframe)
{
localMessage = "06=>" + currentframe.ToString();
bm.SelectActiveFrame(FrameDimension.Page, currentframe);
localMessage = "07=>" + currentframe.ToString();
img = iTextSharp.text.Image.GetInstance(bm, ImageFormat.Bmp);
localMessage = "08=>" + currentframe.ToString();
img.ScalePercent(72f / img.DpiX * 100);
localMessage = "09=>" + currentframe.ToString();
img.SetAbsolutePosition(0, 0);
localMessage = "10=>" + currentframe.ToString();
iTextSharp.text.Rectangle pageRect = new iTextSharp.text.Rectangle(0, 0, img.ScaledWidth, img.ScaledHeight);
localMessage = "11=>" + currentframe.ToString();
document.SetPageSize(pageRect);
localMessage = "12=>" + currentframe.ToString();
document.NewPage();
localMessage = "13=>" + currentframe.ToString();
document.Add(img);
}
localMessage = "14";
bm.Dispose();
localMessage = "15";
document.Close();
localMessage = "16";
stream.Close();
}
}
catch (Exception exception)
{
string msg = exception.Message + "\r\n" +
"Coversion Error--\r\n" +
"\tinput file name: " + file + "\r\n" +
"\toutput file name: " + pdffilename + "\r\n" +
"\tlocal message" + localMessage + "\r\n";
Console.WriteLine(msg);
SaveError(msg);
throw;
}
}
The "local message" is always "06=>n", where n is the 0-based index of the frame that transitions to a new format.
Does anyone know why this is happening or how to fix it?
Following is the code to retrieve image from database and then saving it to a folder.
public string BinarytoNewsImage(int ID)
{
byte[] btimage = null;
string image = "";
string filename = null;
int mediaid;
DataSet dsNews = new DataSet();
adp = new SqlDataAdapter("Select Top 1 * from tblNew Where intNewId=" + ID, offcon);
adp.Fill(dsNews, "tblNews1");
if (dsNews.Tables["tblNews1"].Rows.Count > 0)
{
if (dsNews.Tables["tblNews1"].Rows[0]["strImage"] != DBNull.Value)
{
btimage = (byte[])dsNews.Tables["tblNews1"].Rows[0]["strImage"];
mediaid = Convert.ToInt32(dsNews.Tables["tblNews1"].Rows[0]["intMediaId"].ToString());
filename = dsNews.Tables["tblNews1"].Rows[0]["strfilename"].ToString();
image = BinarytoImage(btimage, mediaid);
}
else
{
filename = dsNews.Tables["tblNews1"].Rows[0]["strfilename"].ToString();
image = "http://www.patrika.com/media/" + filename;
}
}
return image;
}
public string BinarytoImage(byte[] stream, int ID)
{
string ImagePath = "";
string Image = ID + ".jpg";
var URL = System.Configuration.ConfigurationManager.AppSettings["ImagePath"].ToString();
string FolderName = new Uri(URL).LocalPath;
var help = HttpContext.Current.Server.MapPath(FolderName);
if (Directory.Exists(HttpContext.Current.Server.MapPath(FolderName)))
{
string[] files = Directory.GetFiles(HttpContext.Current.Server.MapPath(FolderName), ID + ".jpg");
if (files.Length > 0)
{
ImagePath = URL + ID + ".jpg";
}
else
{
using (MemoryStream MS = new MemoryStream(stream, 0, stream.Length))
{
MS.Write(stream, 0, stream.Length);
System.Drawing.Image img = System.Drawing.Image.FromStream(MS);
img.Save(help + ID + ".jpg", System.Drawing.Imaging.ImageFormat.Gif);
img.Dispose();
img = null;
ImagePath = URL + ID + ".jpg";
}
}
}
return ImagePath;
}
Everything is working fine the images are saving to a folder but my problem is images are getting blur after retrieval.
I just don't know the reason as when I am using another code for retrieval than images are coming fine but are not saved to folder:
DataSet dsNews = new DataSet();
adp = new SqlDataAdapter("Select Top 1 * from tblNew Where intNewId=901371", con);
adp.Fill(dsNews, "tblNews1");
if (dsNews.Tables["tblNews1"].Rows[0]["strImage"] != DBNull.Value)
{
byte[] btimage = (byte[])dsNews.Tables["tblNews1"].Rows[0]["strImage"];
Response.ContentType = "image/jpeg";
Response.BinaryWrite(btimage);
}
I need those images to be saved to folder so that I don't have to call database after once image comes.
Wouldn't it help to change this line
img.Save(help + ID + ".jpg", System.Drawing.Imaging.ImageFormat.Gif);
to store it as JPEG rather? as that's the source format
EDIT:
Your are not moving the stream pointer back to the start.
Try change these lines:
using (MemoryStream MS = new MemoryStream(stream, 0, stream.Length))
{
MS.Write(stream, 0, stream.Length);
System.Drawing.Image img = System.Drawing.Image.FromStream(MS);
...
To
using (MemoryStream MS = new MemoryStream(stream, 0, stream.Length))
{
MS.Write(stream, 0, stream.Length);
MS.Seek(0, SeekOrigin.Begin);
System.Drawing.Image img = System.Drawing.Image.FromStream(MS);
...
I write the common method, all is ok.
Maybe your byte[]stream is not right,pls check.
byte[] stream = File.ReadAllBytes(#"D:\YWG\123.jpg");
using (MemoryStream MS = new MemoryStream(stream, 0, stream.Length))
{
MS.Write(stream, 0, stream.Length);
using (Image img = Image.FromStream(MS))
{
img.Save(#"D:\dd.jpg", System.Drawing.Imaging.ImageFormat.Gif);
}
}
I see the dest file "dd.jpg" is ok.