I already did a code for print label that is working fine on usps server . I just need to print pdf. How can I do this?
private void BindDetail()
{
//to test the upsp used below code
USPSManager m = new USPSManager("USERID", false);
Package p = new Package();
p.FromAddress.Contact = "John Smith";
p.FromAddress.Address2 = "475 L'Enfant Plaza, SW";
p.FromAddress.City = "Washington";
p.FromAddress.State = "DC";
p.FromAddress.Zip = "20260";
p.FromAddress.ZipPlus4 = "2060";
p.ToAddress.Contact = "Tom Customer";
p.ToAddress.Address1 = "STE 201";
p.ToAddress.Address2 = "6060 PRIMACY PKWY";
p.ToAddress.City = "Memphis";
p.ToAddress.State = "TN";
p.ToAddress.Zip = "20219";
p.ToAddress.ZipPlus4 = "2022";
p.WeightInOunces = 2;
p.ServiceType = ServiceType.Priority;
p.SeparateReceiptPage = false;
p.LabelImageType = LabelImageType.PDF;
p.PackageSize = PackageSize.Regular;
p.PackageType = PackageType.Flat_Rate_Box;
// p.ShippingLabel=
p = m.GetDeliveryConfirmationLabel(p);
}
As you mentioned that you already did the code and you are getting the response form server ; then in Order to print the label you just need to convert GetDeliveryConfirmationLabel to an image, you'll have a file called delivery_confirm.tif you can print that into an image. You can use the following from base64String to image
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;
}
Related
I have valid base64 image . I Convert it to image .
For saving with Image.Save(Path)
I have Gdi+ error .
when i try to save with bitmap . the image will save but the image is complete black Like
And here is my code
var encode = EncodeBase64(model.Base64Photo);
//model.Base64Photo = model.Base64Photo.Replace("data:image/png;base64,", "").Replace("data:image/jpeg;base64,", "");
//var imageBytes = Convert.FromBase64String(encode);
var ms = new MemoryStream(encode);
var returnImage = Image.FromStream(ms);
var bitmap = new Bitmap(returnImage);
bitmap.Save($#"C:\inetpub\wwwroot\Dropbox\Websites\2.fidilio.com\Storage\Images\animal\storage\images\animal\{model.Name}-{model.Email}.jpg", ImageFormat.Jpeg);
bitmap.Dispose();
public byte[] EncodeBase64(string data)
{
string s = data.Trim().Replace(" ", "+").Replace("-", "+").Replace("/", "+");
if (s.Length % 4 > 0)
s = s.PadRight(s.Length + 4 - s.Length % 4, '=');
return Convert.FromBase64String(s);
}
I confused so much that where is the problem
It looks like you're making memory stream from string, am I right? You should make memory stream from byte array, like this.
string s = "iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAAAAAAcD2kOAAACOklEQVR4Ae3YhbIdIQwA0H7YBshzd3d3d7sKJO+vqwxzty4L7UyTkfU9K0CAN/iXQmCBBf5XYIEFFlhggQXeeqr9dDxvVgi/2F+IeoVw/VfgWoVw7VfgF4H/HHbE5L+uEZNLBnt7c3Rao6+w3t0cntUpEeyfJzRAzxF96b5MalB9p5QEdq3RAhG1virL8YgKR6qG+aj4uK5G2q7kxiMw7ZPAK/BpA/a55MYjpq/hUsBrAda9NV+GwxE90EwB07kKW7BSeuV4BBYpSal2U+GVDd5RSW4P67A7CUw3xmAoRV/71rDKiRoQXoKwrU65BB8qRN1X94lg/9KjQ/kaarkyHAp7GtjyNoQdsMOd8DqgGrUuGezawyq8cs+zj66zIxr1BSVMi3waq9QiR/j1TCHMkU0Axz6Xn47l6+g1fFp+7tem6yEtTHdoQmU2B56988R3QwphgxP3QHi1wCCryZOn+svVUpdCPdBwiWFf69UYQqnu3h4NBhGOOHmfi/cBY5hPbZkaty4pHOqOwnIYfU0Zepl0obEcsEBZurc0C+UX7nnyWWD/0GU6DxZbnKlDz+tFxzE12HSZYN/o1xgDTjjbEIYPIR5Sk85mg50dV7Em31I+2NK1DuULljjraJEWIHR1X3xW2D93q49VaZczj4/5FAsFsOSyD8zpYXV68czlh61nIvo/50AErlUIP5D/6aDHCuHFk7OfjpMVma8WWGCBBRZYYIEFFlhggQUWWGCBBRZYYIEFFlhggQV+B9418JaaYBt6AAAAAElFTkSuQmCC";
var imageBytes = Convert.FromBase64String(s);
var ms = new MemoryStream(imageBytes);
var returnImage = Image.FromStream(ms);
var bitmap = new Bitmap(returnImage);
//bitmap.Save($#"C:\inetpub\wwwroot\Dropbox\Websites\2.fidilio.com\Storage\Images\animal\storage\images\animal\{model.Name}-{model.Email}.jpg", ImageFormat.Jpeg);
bitmap.Save(#"c:\temp\img.jpg");
bitmap.Dispose();
I wrote this code
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Now I want to check ms text. How can I do that?
With this code, you can encode the image Bytes into an hexadecimal string representation:
Byte[] a = ms.ToArray();
String text = BitConverter.ToString(a);
You can try with this code....
var url = HostingEnvironment.MapPath("~/Images/" + name);
byte[] myByte = System.IO.File.ReadAllBytes(url);
using (MemoryStream ms = new MemoryStream())
{
ms.Write(myByte, 0, myByte.Length);
i = System.Drawing.Image.FromStream(ms);
System.Drawing.Image imageIn = i.GetThumbnailImage(100, 100,()=> false, IntPtr.Zero);
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
var storedUrl = "data:image;base64," + Convert.ToBase64String(ms.ToArray());
return storedUrl;
}
I use this to send the image as string:
string path = #"C:\Users\user6\Pictures\wp\tinypotato.jpg";
string myString = Convert.ToBase64String(File.ReadAllBytes(path))
Debug.WriteLine(myString);
...
BR!
I am busy trying to understand how to work with images from a website -> service -> email.
What I have done so far is converting the image to base64 then uploading it to my service. Next I convert it to a byte array and then store it into my database.
At the same time when inserting the byte into my database I want to send the image by attaching it to an email.
At this time the attachment is only a file that I cannot open, so I guess it is just a byte array and not an Image.
C#
public string SendEmail(string send)
{
try
{
TestDb db = new TestDb();
TestImage result = new TestImage();
string[] arData = send.Split('|');
byte[] bytes = new byte[arData[0].Length * sizeof(char)];
System.Buffer.BlockCopy(arData[0].ToCharArray(), 0, bytes, 0, bytes.Length);
result.TestImg = bytes;
result.TestId = int.Parse(arData[1].ToString());
db.TestImage.Attach(result);
db.TestImage.Add(result);
db.SaveChanges();
string foto = "name";
Attachment att = new Attachment(new MemoryStream(bytes), foto);
MailMessage mail = new MailMessage();
NetworkCredential cred = new NetworkCredential("Test#gmail.com", "Test123");
mail.To.Add("Test#gmail.com");
mail.Subject = "subject Test";
mail.Attachments.Add(att);
mail.From = new MailAddress("Test#gmail.com");
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = cred;
smtp.Send(mail);
return result.Id.ToString();
}
catch (Exception)
{
throw;
}
}
Angularjs
$scope.link = '\img\ionic.png';
var imageData=$base64.encode($scope.link);
$scope.sendimg = function() {
console.log(imageData);
$http.post("http://localhost:53101/TruckService.svc/sendEmail/" + imageData + '|' + 1
)
.success(function(data) {
})
.error(function(data) {
console.log("failure");
})
}
I think the problem is with converting image to base64. So check whether you have correct image in imageData by convert it back to an image.
You can use online tools to converto base64 to image Link
So if it's the problem, try to convert your image as below,
function toDataUrl(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
toDataUrl('url', function(base64Img){
// Base64DataURL
});
In my case it comes from my Resources. But in the end its the same. After maken a byte[] I attach it like this:
byte[] logo = BmpToBytes_MemStream(Properties.Resources.gcs_logo);
emailMessage.Attachments.AddFileAttachment("logo.jpg", logo);
emailMessage.Attachments[emailMessage.Attachments.Count - 1].IsInline = true;
emailMessage.Attachments[emailMessage.Attachments.Count - 1].ContentId = "gcs_logo.jpg";
private static byte[] BmpToBytes_MemStream(Bitmap bmp)
{
byte[] bmpBytes = null;
using (MemoryStream ms = new MemoryStream())
{
// Save to memory using the Jpeg format
bmp.Save(ms, ImageFormat.Jpeg);
// read to end
bmpBytes = ms.GetBuffer();
bmp.Dispose();
}
return bmpBytes;
}
Hope this helps.
I am using zxing library to generate and decode the QR codes. I my application I am generating QR code dynamically and sending the file containing QR by fax API. If I get this fax message from the api and decode it, Qr code is read successfully, but when I send a scanned copy of this file by fax and then receive and read it I am unable to do that. But if I try to read this file using my mobile Qr application it properly reads the Qr code. I am unable to find a solution how to read this file.
Methods used for encoding:
public static System.Drawing.Image GenerateJSONQrCode(QRJsonFax model)
{
var jsonString = JsonConvert.SerializeObject(model);
//encrypt json string
jsonString = Hugo.BLL.Utilities.EncryptionHelper.EncryptQR(jsonString, FaxSetting.IsUseHashing);
var bw = new ZXing.BarcodeWriter();
var encOptions = new ZXing.Common.EncodingOptions() { Width = 200, Height = 200, Margin = 0 };
bw.Options = encOptions;
bw.Format = ZXing.BarcodeFormat.QR_CODE;
var image = new Bitmap(bw.Write(Compress(jsonString)));
return image;
}
private static string Compress(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
var ms = new MemoryStream();
using (var zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
ms.Position = 0;
byte[] compressed = new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);
byte[] gzBuffer = new byte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return Convert.ToBase64String(gzBuffer);
}
Methods used for encoding and decoding
public static FaxReceiver.QrFinder DecodeQrCode(string imagePathToDecode)
{
long userId = 0;
Bitmap bitmapImage = (Bitmap)Image.FromFile(imagePathToDecode);
ZXing.BarcodeReader barcodeReader = new BarcodeReader() { AutoRotate = true, TryHarder = true }; ;
Result decode = barcodeReader.Decode(bitmapImage);
var scanResult = string.Empty;
if (decode != null)
{
scanResult= Decompress(decode.Text);
}
if (!string.IsNullOrWhiteSpace(scanResult))
{
//decrypt Qr received
var decryptedString = DecryptionHelper.Decrypt(scanResult, FaxSetting.IsUseHashing);
//deserialize JSON received
var resultJson = JsonConvert.DeserializeObject<QRJsonFax>(decryptedString);
if (resultJson != null)
{
long.TryParse(resultJson.UserID.ToString(), out userId);
return new QrFinder()
{
FilePath = imagePathToDecode,
UserId = userId,
PageNo = 0,
DataSourceID = resultJson.DataSourceID,
InboundFaxTypeID = resultJson.InboundFaxTypeID
};
}
}
return null;
}
private static string Decompress(string compressedText)
{
byte[] gzBuffer = Convert.FromBase64String(compressedText);
using (var ms = new MemoryStream())
{
int msgLength = BitConverter.ToInt32(gzBuffer, 0);
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
byte[] buffer = new byte[msgLength];
ms.Position = 0;
using (var zip = new GZipStream(ms, CompressionMode.Decompress))
{
zip.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
File containing Qr code
The problem is that the QR Decoder is getting confused by the gaps between the pixels in your faxed image. If we zoom into a corner of it, this is what we see.
The scanner is looking for solid black squares to identify the QR code.
If we shrink the image by 50%, it becomes readable.
See for yourself at http://zxing.org/w/decode?u=http%3A%2F%2Fi.stack.imgur.com%2FSCYsd.png
I would suggest that after receiving the faxed image, you should either shrink it, or apply a filter to ensure that the QR codes are solid black. You could also look at sending it at a smaller resolution to see if that helps.
i need to convert the images(fetching from web service) into base64String to store them in the SQLite database.
EDIT: I use ImageOpened so that the image is loaded/downloaded before I convert them into base64String but ImageOpened doest run. How do I achieve this task ? I mean to convert array of images into base64.
this is my code:
public async void LoadData()
{
//get Json
string str = await Helper.getJSON();
//Deserialize json
MainClass apiData = JsonConvert.DeserializeObject<MainClass>(str);
//the problem loop
for (int i = 0; i < apiData.Categories.Count;i++ )
{
//apiData.Categoriesp[i].icon_image is the url of the image
BitmapImage image = new BitmapImage(new Uri(apiData.Categories[i].icon_image,UriKind.RelativeOrAbsolute));
//it never runs
image.ImageOpened += (s, e) =>
{
//code for conversion of image into memory stream
image.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap wb = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
//setting imageInSql property of the list (but it never runs)
apiData.Categories[i].imageInSql = base64String;
};
}
//Inserting into database
using(var db= new SQLiteConnection(App.dbPath)){
//geting null in imageinSql property.
db.InsertAll(apiData.Categories,typeof(Category));
}
}
Thanks in advance.
For me it looks like a you are setting CreateOptions property inside the event handler.
image.ImageOpened += (s, e) =>
{
//code for conversion of image into memory stream
image.CreateOptions = BitmapCreateOptions.None;
You should do this like-
image.CreateOptions = BitmapCreateOptions.None;
image.ImageOpened += (s, e) =>
{
Try below code.
public async void LoadData()
{
//get Json
string str = await Helper.getJSON();
//Deserialize json
MainClass apiData = JsonConvert.DeserializeObject<MainClass>(str);
//the problem loop
for (int i = 0; i < apiData.Categories.Count;i++ )
{
//apiData.Categoriesp[i].icon_image is the url of the image
BitmapImage image = new BitmapImage(new Uri(apiData.Categories[i].icon_image,UriKind.RelativeOrAbsolute));
image.CreateOptions = BitmapCreateOptions.None
//it never runs
image.ImageOpened += (s, e) =>
{
//code for conversion of image into memory stream
WriteableBitmap wb = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
//setting imageInSql property of the list (but it never runs)
apiData.Categories[i].imageInSql = base64String;
};
}
//Inserting into database
using(var db= new SQLiteConnection(App.dbPath)){
//geting null in imageinSql property.
db.InsertAll(apiData.Categories,typeof(Category));
}
}