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;
}
}
}
});
}
Related
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.
How to migrate using QRCoder; to using ZXing; in asp.net , Because I learn How to Generate QR Code Using ASP.NET with
https://www.c-sharpcorner.com/blogs/how-to-generate-qr-code-using-asp-net
website but code in website use QRCoder library not support UTF-8 encoding , I have migrate QRCoder library code at line 16 - line 31 to ZXing library with
https://github.com/ritesh9835/QrCode
https://github.com/ritesh9835/QrCode/blob/master/QRcodeDemo/QRcodeDemo/Controllers/HomeController.cs
website instead QRCoder library code at line 16 - line 31 (Sample library code QRCoder and Zxing at the bottom).
QRCoder Library code.
using QRCoder;
using System;
using System.Drawing;
using System.IO;
namespace QRCode_Demo
{
public partial class QRCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q);
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
using (Bitmap bitMap = qrCode.GetGraphic(20))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
}
}
}
}
Zxing Library code to instead QRCoder library code at line 16 - line 31.
private string GenerateQRCode(string qrcodeText)
{
string folderPath = "~/Images/";
string imagePath = "~/Images/QrCode.jpg";
// create new Directory if not exist
if (!Directory.Exists(Server.MapPath(folderPath)))
{
Directory.CreateDirectory(Server.MapPath(folderPath));
}
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
var result = barcodeWriter.Write(qrcodeText);
string barcodePath = Server.MapPath(imagePath);
var barcodeBitmap = new Bitmap(result);
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(barcodePath, FileMode.Create, FileAccess.ReadWrite))
{
barcodeBitmap.Save(memory, ImageFormat.Jpeg);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
return imagePath;
}
You mean like this ?
protected void btnGenerate_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options.Margin = 0;
barcodeWriter.Options.Width = 150;
barcodeWriter.Options.Height = 150;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
using (Bitmap bitMap = barcodeWriter.Write(code))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
}
}
I am getting a image from a server which is pretty large around 15MB but i want to keep the Aspect Ratio but compress the size of the file because I am loading multiple files that around the same size? these Image are downloaded as BitMaps and Used SetImageBitmap to display the image
You can do this by converting the image to a jpeg or png. This is quick and dirty implementation of a Bitmap to PNG conversion routine:
public string ResizeImage(string sourceFilePath)
{
Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeFile (sourceFilePath);
string newPath = sourceFilePath.Replace(".bmp", ".png");
using (var fs = new FileStream (newPath, FileMode.OpenOrCreate)) {
bmp.Compress (Android.Graphics.Bitmap.CompressFormat.Png, 100, fs);
}
return newPath;
}
It makes assumptions on the file extension but that can modified fairly easily.
Here is the full sample I used to verify the compression:
public class MainActivity : Activity
{
public const string BITMAP_URL = #"http://www.openjpeg.org/samples/Bretagne2.bmp";
public string ResizeImage(string sourceFilePath)
{
Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeFile (sourceFilePath);
string newPath = sourceFilePath.Replace(".bmp", ".png");
using (var fs = new FileStream (newPath, FileMode.OpenOrCreate)) {
bmp.Compress (Android.Graphics.Bitmap.CompressFormat.Png, 100, fs);
}
return newPath;
}
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate {
System.Threading.Tasks.Task.Run( () => {
RunOnUiThread( () => Toast.MakeText(this, "Downloading file", ToastLength.Long).Show());
string downloadFile = DownloadSourceImage(BITMAP_URL);
RunOnUiThread( () => Toast.MakeText(this, "Rescaling image: " + downloadFile, ToastLength.Long).Show());
string convertedFile = ResizeImage(downloadFile);
var bmpFileSize = (new FileInfo(downloadFile)).Length;
var pngFileSize = (new FileInfo(convertedFile)).Length;
RunOnUiThread( () => Toast.MakeText(this, "BMP is " + bmpFileSize + "B. PNG is " + pngFileSize + "B.", ToastLength.Long).Show());
});
};
}
public string DownloadSourceImage(string url)
{
System.Net.WebClient client = new System.Net.WebClient ();
string fileName = url.Split ('/').LastOrDefault ();
string downloadedFilePath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, fileName);
if (File.Exists (downloadedFilePath) == false) {
client.DownloadFile (url, downloadedFilePath);
}
return downloadedFilePath;
}
}
You can compress the image using other file formats (eg. jpeg).
Or you can resize the image while maintaining the aspect ratio.
I want to be able to save images in IsolatedStorage, and later get it.
for this purpose I wrote a helper which I want to access it from everywhere in my app:
for creating an image:
public static void SaveImage(Stream image, string name)
{
try
{
IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (!isolatedStorage.DirectoryExists("MyImages"))
{
isolatedStorage.CreateDirectory("MyImages");
}
var filePath = Path.Combine("MyImages", name + ".jpg");
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, isolatedStorage))
{
StreamWriter sw = new StreamWriter(fileStream);
sw.Write(image);
sw.Close();
}
}
catch (Exception ex)
{
throw new Exception("failed");
}
}
and for getting that image again:
public static BitmapImage Get(string name)
{
try
{
IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
var filePath = Path.Combine("MyImages", name + ".jpg");
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Open, isolatedStorage))
{
BitmapImage image = new BitmapImage();
image.SetSource(fileStream);
return image;
}
}
catch (Exception ex)
{
throw new Exception("failed");
}
}
The problem appears when I try to set source of image I get this error message:
The component cannot be found. (Exception from HRESULT: 0x88982F50)
Assuming you have the right Capabilities under your WMAppManifest.xml what you need is:
public static void SaveImage(Stream image, string name)
{
var bitmap = new BitmapImage();
bitmap.SetSource(attachmentStream);
var wb = new WriteableBitmap(bitmap);
var temp = new MemoryStream();
wb.SaveJpeg(temp, wb.PixelWidth, wb.PixelHeight, 0, 50);
using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!myIsolatedStorage.DirectoryExists("MyImages"))
{
myIsolatedStorage.CreateDirectory("MyImages");
}
var filePath = Path.Combine("MyImages", name + ".jpg");
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, myIsolatedStorage))
{
fileStream.Write(((MemoryStream)temp).ToArray(), 0, ((MemoryStream)temp).ToArray().Length);
fileStream.Close();
}
}
}
That should work and store your image as a jpeg into your desired directory. if it doesn't, make sure that the create directory and Path.Combine() methods are being used correctly.
I want to upload my recorded file to skydrive and I am using these codes
For recording;
void StopRecording()
{
// Get the last partial buffer
int sampleSize = microphone.GetSampleSizeInBytes(microphone.BufferDuration);
byte[] extraBuffer = new byte[sampleSize];
int extraBytes = microphone.GetData(extraBuffer);
// Stop recording
microphone.Stop();
// Create MemoInfo object and add at top of collection
int totalSize = memoBufferCollection.Count * sampleSize + extraBytes;
TimeSpan duration = microphone.GetSampleDuration(totalSize);
MemoInfo memoInfo = new MemoInfo(DateTime.UtcNow, totalSize, duration);
memoFiles.Insert(0, memoInfo);
// Save data in isolated storage
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = storage.CreateFile("/shared/transfers/" + memoInfo.FileName))
{
// Write buffers from collection
foreach (byte[] buffer in memoBufferCollection)
stream.Write(buffer, 0, buffer.Length);
// Write partial buffer
stream.Write(extraBuffer, 0, extraBytes);
}
}
}
For Uploading file;
async void OnSaveButtonClick(object sender, RoutedEventArgs args)
{
Button btn = sender as Button;
MemoInfo clickedMemoInfo = btn.Tag as MemoInfo;
memosListBox.SelectedItem = clickedMemoInfo;
if (this.client == null)
{
gridSingin.Visibility = Visibility.Visible;
memosListBox.Visibility = Visibility.Collapsed;
}
else
{
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var fileStream = store.OpenFile(clickedMemoInfo.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
LiveOperationResult res = await client.BackgroundUploadAsync("me/skydrive",
new Uri("/shared/transfers/" + clickedMemoInfo.FileName, UriKind.Relative),
OverwriteOption.Overwrite
);
InfoText.Text = "File " + clickedMemoInfo.FileName + " uploaded";
}
}
}
}
But I am gettin error in here
LiveOperationResult res = await client.BackgroundUploadAsync("me/skydrive", new Uri("/shared/transfers/" + clickedMemoInfo.FileName, UriKind.Relative), OverwriteOption.Overwrite);
I am getting this error;
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in System.Windows.ni.dll
Could you help me, please?
You cannot have the file open when trying to upload. Try doing this.
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.FileExists(fileName))
{
client.BackgroundUploadAsync("me/skydrive", new Uri(fileName, UriKind.Relative),
OverwriteOption.Overwrite);
}
}