I think i need to store the string s and bitmap bmp in an array then i think i have to pick one image in the bmp array to show in the picture box but im not sure how.
public partial class capstoneProjectForm : Form
{
string imageName;
//string[] a;
Bitmap[] bit;
string[] folder;
int numOfPics;
int num = 0;
public capstoneProjectForm()
{
InitializeComponent();
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
// a = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
string resFolder = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources");
foreach (string s in Directory.EnumerateFiles(resFolder, "*.jpg"))
{
using (Bitmap bmp = new Bitmap(s))
{
}
if (s.Equals(imageName))
{
pictureBox.Image = ;
}
}
Related
I have code for saving Layout as bitmap
Here it is
public static class App
{
public static Java.IO.File _file;
public static Java.IO.File _dir;
public static Bitmap bitmap;
}
[Activity(Label = "SaveViewAsBitMap", ScreenOrientation = ScreenOrientation.Landscape, Theme = "#android:style/Theme.Black.NoTitleBar")]
public class Badge : Activity
{
public static string name_from_activity;
public static string surname_from_activity;
public string inn_from_activity;
private ImageView _imageView;
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
// Make it available in the gallery
Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
Uri contentUri = Uri.FromFile(App._file);
mediaScanIntent.SetData(contentUri);
SendBroadcast(mediaScanIntent);
// Display in ImageView. We will resize the bitmap to fit the display
// Loading the full sized image will consume to much memory
// and cause the application to crash.
int height = Resources.DisplayMetrics.HeightPixels;
int width = _imageView.Height;
App.bitmap = App._file.Path.LoadAndResizeBitmap(width, height);
if (App.bitmap != null)
{
_imageView.SetImageBitmap(App.bitmap);
App.bitmap = null;
}
// Dispose of the Java side bitmap.
GC.Collect();
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
TextView bt1 = FindViewById<TextView>(Resource.Id.Surname);
bt1.Click += Bt1_Click;
name_from_activity = Intent.GetStringExtra("Name");
surname_from_activity = Intent.GetStringExtra("Surname");
inn_from_activity = Intent.GetStringExtra("INN");
TextView Name = FindViewById<TextView>(Resource.Id.Name);
Name.Text = name_from_activity;
TextView Surname = FindViewById<TextView>(Resource.Id.Surname);
Surname.Text = surname_from_activity;
string path = "Fonts/proximanovaregular.otf";
Typeface tf = Typeface.CreateFromAsset(Assets, path); //Custom fonts for TextBoxes
Name.Typeface = tf;
Surname.Typeface = tf;
var barcodeWriter = new ZXing.Mobile.BarcodeWriter //Creating qr code using Intent data
{
Format = ZXing.BarcodeFormat.QR_CODE,
Options = new ZXing.Common.EncodingOptions //Options for QR code dimensions
{
Width = 600,
Height = 600
}
};
ImageView qr = FindViewById<ImageView>(Resource.Id.qr);
var bitmap = barcodeWriter.Write(inn_from_activity);
qr.SetImageBitmap(bitmap);
if (IsThereAnAppToTakePictures())
{
CreateDirectoryForPictures();
_imageView = FindViewById<ImageView>(Resource.Id.photo);
TakeAPicture();
}
}
//Button handler for bitmap
private void Bt1_Click(object sender, System.EventArgs e)
{
View v = FindViewById<LinearLayout>(Resource.Id.badge2);
Bitmap myBitMap = createViewBitmap(v);
Drawable drawable = new BitmapDrawable(myBitMap);
//img.SetBackgroundDrawable(drawable);
// MediaStore.Images.Media.InsertImage(ContentResolver, myBitMap, "title", "description");
saveImage(myBitMap);
Intent mediaScanIntent2 = new Intent(Intent.ActionMediaScannerScanFile);
Java.IO.File myFile = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + "/DCIM/Camera", name_from_activity.ToString() + surname_from_activity.ToString() + ".jpg");
Android.Net.Uri contentUri = Android.Net.Uri.FromFile(myFile);
mediaScanIntent2.SetData(contentUri);
SendBroadcast(mediaScanIntent2);
}
//Creating bitmap from view via Canvas
public Bitmap createViewBitmap(View v)
{
Bitmap bitmap = Bitmap.CreateBitmap(v.Width, v.Height,
Bitmap.Config.Argb8888);
Canvas canvas = new Canvas(bitmap);
v.Draw(canvas);
return bitmap;
}
//Check if directory exists, if no, create it
private void CreateDirectoryForPictures()
{
App._dir = new Java.IO.File(
Environment.GetExternalStoragePublicDirectory(
Environment.DirectoryPictures), "CameraAppDemo");
if (!App._dir.Exists())
{
App._dir.Mkdirs();
}
}
//Returning avialable activities
private bool IsThereAnAppToTakePictures()
{
Intent intent = new Intent(MediaStore.ActionImageCapture);
IList<ResolveInfo> availableActivities =
PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);
return availableActivities != null && availableActivities.Count > 0;
}
//Method for opening default Camera Activity and making photo
private void TakeAPicture()
{
Intent intent = new Intent(MediaStore.ActionImageCapture);
App._file = new Java.IO.File(App._dir, String.Format("myPhoto_{0}.jpg", Guid.NewGuid()));
intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(App._file));
StartActivityForResult(intent, 0);
}
//Method for saving image to device
public static void saveImage(Bitmap bmp)
{
try
{
using (var os = new System.IO.FileStream(Android.OS.Environment.ExternalStorageDirectory + "/DCIM/Camera/" + name_from_activity.ToString()+surname_from_activity.ToString() + ".jpg", System.IO.FileMode.CreateNew))
{
bmp.Compress(Bitmap.CompressFormat.Jpeg, 95, os);
}
}
catch (Exception e)
{
}
}
}
}
I need to save picture in 370*204 resolution
I try it like this
public Bitmap createViewBitmap(View v)
{
Bitmap bitmap = Bitmap.CreateBitmap(370, 204,
Bitmap.Config.Argb8888);
Canvas canvas = new Canvas(bitmap);
v.Draw(canvas);
return bitmap;
}
But it not works, it saves only part of layout.
How I need to write code?
Thank's for help.
I had build a prototype for one other project that I'm using...
Try this repository
This code Bitmap.CreateBitmap(370, 204,Bitmap.Config.Argb8888); will cut the source bitmap with width 370 and height 204. The bitmap not be scaled. Because you are still use the view to draw a bitmap.
When you get the view bitmap you need to zoom the bitmap:
public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight)
{
int width = bm.Width;
int height = bm.Height;
float scaleWidth = ((float)newWidth) / width;
float scaleHeight = ((float)newHeight) / height;
Matrix matrix = new Matrix();
matrix.PostScale(scaleWidth, scaleHeight);
Bitmap newbm = Bitmap.CreateBitmap(bm, 0, 0, width, height, matrix, true);
return newbm;
}
public Bitmap createViewBitmap2(View v)
{
Bitmap bitmap = Bitmap.CreateBitmap(v.Width, v.Height,Bitmap.Config.Argb8888);
Canvas canvas = new Canvas(bitmap);
v.Draw(canvas);
return zoomImg(bitmap, 370, 204);
}
I'm plotting some scatter graphs from SQL data in a c# program. I would like automatically save these graphs as they populate. I have the following code which saves the Jpeg files, but when I open them, they are empty. I'm plotting multiple graphs at once.
Any help is appreciated.
public partial class XYplotForm : Form
{
public XYplotForm()
{
InitializeComponent();
}
public void Plot(Double[] freq, Double[] amp, Double[] bw, string name)
{
scatterGraph1.PlotXY(freq, amp);
tbName.Text = name;
Bitmap image = new Bitmap(scatterGraph1.Width, scatterGraph1.Height);
Rectangle target_bounds = default(Rectangle);
target_bounds.Width = scatterGraph1.Width;
target_bounds.Height = scatterGraph1.Height;
target_bounds.X = 0;
target_bounds.Y = 0;
scatterGraph1.DrawToBitmap(image, target_bounds);
string filename = "C:\\Graph\\" + name + ".Jpeg";
image.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
xyForm = new XYplotForm();
xyForm.Plot(freqLC40, ampMaxLC40, "LC-40 Max Amplitude");
xyForm.Show();
Bitmap image = new Bitmap(xyForm.Width, xyForm.Height);
System.Drawing.Rectangle target_bounds = default(System.Drawing.Rectangle);
target_bounds.Width = xyForm.Width;
target_bounds.Height = xyForm.Height;
target_bounds.X = 0;
target_bounds.Y = 0;
xyForm.DrawToBitmap(image, target_bounds);
string filename = "C:\\Graph\\LC40_Max Amplitude.Png";
image.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
I'm trying to load an image file from harddisk to the image widget in GTK#.I know that Pixbuf is used to represent the image.In .net i had used Bitmap b=Bitmap.from File ("c:\windows\file.jpg")
and assigned PictureBox=b;
How can i do this with Image Widget
Update:
I tried
protected void OnButton2ButtonPressEvent (object o, ButtonPressEventArgs args)
{
var buffer = System.IO.File.ReadAllBytes ("i:\\Penguins.jpg");
var pixbuf = new Gdk.Pixbuf (buffer);
image103.Pixbuf = pixbuf;
}
But it does not work.
Try this:
var buffer = System.IO.File.ReadAllBytes ("path\\to\\file");
var pixbuf = new Gdk.Pixbuf (buffer);
image.Pixbuf = pixbuf;
Also you may create a pixbuf like this:
var pixbuf = new Gdk.Pixbuf ("path\\to\\file");
But when I tried to use this constructor with path containing some russian symbols I had an exception because of wrong encoding.
Update
I don't know any legacy method to set in gtk# image stretch option and I usually solve this problem with creation of new control. So right click on the project->Add->Create Widget and set the name to ImageControl. Add Image on created widget. Then edit ImageControl's code like this:
[System.ComponentModel.ToolboxItem (true)]
public partial class ImageControl : Gtk.Bin
{
private Pixbuf original;
private bool resized;
public Gdk.Pixbuf Pixbuf {
get
{
return image.Pixbuf;
}
set
{
original = value;
image.Pixbuf = value;
}
}
public ImageControl ()
{
this.Build ();
}
protected override void OnSizeAllocated (Gdk.Rectangle allocation)
{
if ((image.Pixbuf != null) && (!resized)) {
var srcWidth = original.Width;
var srcHeight = original.Height;
int resultWidth, resultHeight;
ScaleRatio (srcWidth, srcHeight, allocation.Width, allocation.Height, out resultWidth, out resultHeight);
image.Pixbuf = original.ScaleSimple (resultWidth, resultHeight, InterpType.Bilinear);
resized = true;
} else {
resized = false;
base.OnSizeAllocated (allocation);
}
}
private static void ScaleRatio(int srcWidth, int srcHeight, int destWidth, int destHeight, out int resultWidth, out int resultHeight)
{
var widthRatio = (float)destWidth / srcWidth;
var heigthRatio = (float)destHeight / srcHeight;
var ratio = Math.Min(widthRatio, heigthRatio);
resultHeight = (int)(srcHeight * ratio);
resultWidth = (int)(srcWidth * ratio);
}
}
Now you may set pictures with Pixbuf property of ImageControl's widget.
i want to convert a string entered by user to an image..how can it be done?
i tried the following code but i get an argument exception in the line :
WriteableBitmap wbimg = PictureDecoder.DecodeJpeg(memStream);
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes
= StringToAscii(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
public static byte[] StringToAscii(string s)
{
byte[] retval = new byte[s.Length];
for (int ix = 0; ix < s.Length; ++ix)
{
char ch = s[ix];
if (ch <= 0x7f) retval[ix] = (byte)ch;
else retval[ix] = (byte)'?';
}
return retval;
}
void convert()
{
String s = textBox1.Text;
byte[] data = Convert.FromBase64String(EncodeTo64(s));
for (int i = 0; i < data.Length; i++)
{
System.Diagnostics.Debug.WriteLine(data[i]);
}
Stream memStream = new MemoryStream();
memStream.Write(data, 0, data.Length);
try
{
WriteableBitmap wbimg = PictureDecoder.DecodeJpeg(memStream);
image1.Source = wbimg;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
I got what i wanted in the following links.. How can I render text on a WriteableBitmap on a background thread, in Windows Phone 7? and http://blogs.u2u.be/michael/post/2011/04/20/Adding-a-text-to-an-image-in-WP7.aspx Thanks to all those who replied for the initial help! :)
It is the simple way you can convert TextBlock Text into Image
private void convert_Click(object sender, RoutedEventArgs e)
{
Canvas c1 = new Canvas();
TextBlock t = new TextBlock();
t.Text = text1.Text;
t.FontFamily = text1.FontFamily;
t.Foreground = text1.Foreground;
t.FontSize = text1.FontSize;
c1.Children.Add(t);
WriteableBitmap wbmp = new WriteableBitmap(c1, null);
im = new Image();
im.Source = wbmp;
im.Height = 200;
im.Width = 200;
Canvas.SetTop(im, 10);
Canvas.SetLeft(im, 10);
Main_Canvas.Children.Add(im);
}
Here I convert the Textblock Text into Bitmap and then assign it to the image source.
Here is how to writte a string to a bitmap:
Bitmap b = new Bitmap(200, 100);
Graphics g = Graphics.FromImage(b);
g.DrawString("My sample string", new Font("Tahoma",10), Brushes.Red, new Point(0, 0));
b.Save("mypic.png", System.Drawing.Imaging.ImageFormat.Png);
g.Dispose();
b.Dispose();
Shubhi1910 let me know if you need any details to be explained.
I've got an image upload page that works just fine when I only upload the files.
I added a 'Create Thumbnail' function. It looks like the file system has a handle on the images when the thumbnail process starts.
I get the 'unspecified GDI+ error' only when the image is over about 250K. When the files are below 250K, thumbnails are created as expected.
What are my options? Is there an elegant solution here? I want something not hacky.
Also, I am using HttpFileCollection so we can upload multiple images at one time. I've tried to use .Dispose on the Thumbnail creation, but it fails before we get to this point.
public void Upload_Click(object Sender, EventArgs e)
{
string directory = Server.MapPath(#"~\images\");
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string fileName = hpf.FileName;
fileName = fileName.Replace(" ", "");
hpf.SaveAs(fileName);
createThumbnail(fileName);
}
}
}
private void createThumbnail(string filename)
{
Image image = Image.FromFile(filename);
Image thumb = image.GetThumbnailImage(100,100, () => false, IntPtr.Zero);
thumb.Save(filename);
image.Dispose();
thumb.Dispose();
}
Please let me know if this works any better:
public string ImageDirectory { get { return Server.MapPath(#"~\images\"); } }
public void OnUploadClick(object sender, EventArgs e)
{
var files = HttpContext.Request.Files.AllKeys.AsEnumerable()
.Select(k =>HttpContext.Request.Files[k]);
foreach(var file in files)
{
if(file.ContentLength <= 0)
continue;
string savePath = GetFullSavePath(file);
var dimensions = new Size(100, 100);
CreateThumbnail(file,savePath,dimensions);
}
}
private void CreateThumbnail(HttpPostedFile file,string savePath, Size dimensions)
{
using (var image = Image.FromStream(file.InputStream))
{
using (var thumb = image.GetThumbnailImage(dimensions.Width, dimensions.Height, () => false, IntPtr.Zero))
{
thumb.Save(savePath);
}
}
}
private string GetFullSavePath(HttpPostedFile file)
{
string fileName = System.IO.Path.GetFileName(file.FileName).Replace(" ", "");
string savePath = System.IO.Path.Combine(this.ImageDirectory, fileName);
return savePath;
}
Edit -
The foreach should have followed more to this pattern:
var files = HttpContext.Request.Files.AllKeys.AsEnumerable()
.Select(k =>HttpContext.Request.Files[k]);
foreach(var file in files)
{
}
You can try this code to create your thumbnails.
MemoryStream ms = new MemoryStream(File.ReadAllBytes(path));
Bitmap originalBMP = new Bitmap(ms);
int maxWidth = 200;
int maxHeight = 200;
// Calculate the new image dimensions
int origWidth = originalBMP.Width;
int origHeight = originalBMP.Height;
double sngRatio = Convert.ToDouble(origWidth) / Convert.ToDouble(origHeight);
// New dimensions
int newWidth = 0;
int newHeight = 0;
try
{
// max 200 by 200
if ((origWidth <= maxWidth && origHeight <= maxHeight) || origWidth <= maxWidth)
{
newWidth = origWidth;
newHeight = origHeight;
}
else
{
// Width longer (shrink width)
newWidth = 200;
newHeight = Convert.ToInt32(Convert.ToDouble(newWidth) / sngRatio);
}
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.High;
// Draw the new graphic based on the resized bitmap
oGraphics.CompositingQuality = CompositingQuality.HighSpeed;
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
// Save the new graphic file to the server
EncoderParameters p = new EncoderParameters(1);
p.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 70); // Percent Compression
MemoryStream savedBmp = new MemoryStream();
newBMP.Save(savedBmp, ImageCodecInfo.GetImageEncoders()[1], p);
// Once finished with the bitmap objects, we deallocate them.
originalBMP.Dispose();
newBMP.Dispose();
oGraphics.Dispose();
savedBmp.Dispose();
Certainly a bit more work but it does give you greater control.