public ImageWrapper(string fileName, ImageTools imgTools, DirectorySettingsHandler dirSettingsHandler) { imageTools = imgTools; file = fileName; string[] dirs = file.Replace(@"\","/").Split('/'); name = dirs[dirs.Length - 1]; dirSettings = dirSettingsHandler; }
public SubDirectoryWrapper(string dir, string defaultFolderImage, ImageTools imgTools) { directory = dir; defaultImage = defaultFolderImage; imageTools = imgTools; string[] dirs = directory.Replace(@"\","/").Split('/'); dirSettings = new DirectorySettingsHandler(imageTools.cfg.PictureRootDirectory + "/" + directory, dirs[dirs.Length - 1]); }
private void Page_Load(object sender, System.EventArgs e) { try { imageTools = new ImageTools(this); if (!IsPostBack) { BuildDirectories(imageTools.cfg.PictureVirtualDirectory, 0); } } catch { } }
/// <summary> /// /// </summary> /// <param name="dir">Directory to hold contents of</param> public DirectoryWrapper(string dir, ImageTools imgTools) { imageTools = imgTools; directory = dir; dirSettings = new DirectorySettingsHandler(imageTools.cfg.PictureRootDirectory + "/" + directory, Name); // add the sub-directories string[] subDirectories = Directory.GetDirectories(imageTools.cfg.PictureRootDirectory + "/" + directory); foreach (string s in subDirectories) { string[] path = s.Replace("\\", "/").Split('/'); if (path[path.Length - 1] != "thumbs" && path[path.Length - 1] != "webpics" && path[path.Length - 1][0] != '_') { directories.Add(imageTools.GetSubDirectoryWrapper(directory + "/" + path[path.Length - 1])); } } // add pictures string[] files = Directory.GetFiles(imageTools.cfg.PictureRootDirectory + "/" + directory); foreach (string s in files) { string[] path = s.Replace(@"\", "/").Split('/'); string fileName = path[path.Length - 1]; if (fileName[0] != '_') { string extension = null; if (fileName.IndexOf(".") > 0) { string[] parts = fileName.Split('.'); extension = parts[parts.Length - 1]; } if (extension == null) continue; extension = extension.ToLower(CultureInfo.InvariantCulture); if (extension == "jpg" || extension == "png" || extension == "gif") { images.Add(imageTools.GetImageWrapper(directory + "/" + fileName, dirSettings)); } } } }
/// <summary> /// /// </summary> /// <param name="index"></param> /// <param name="imgContain"></param> private void LoadPic(int index, ref ImageTools.Controls.AnimatedImage imgContain) { if (imgContain.Source != null) { if (!OutOfTime(index)) { return; } } if (!Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) MessageBox.Show("网络异常!"); ExtendedImage image = new ImageTools.ExtendedImage(); image.UriSource = new Uri(_bindData[index].Url); imgContain.Source = image; _bindData[index].DownLoadTime = DateTime.Now; }
// ######################################################################################################################################################### public static double[,] BriggsNoiseFilterAndGetMask(double[,] matrix, int percentileThreshold, double binaryThreshold) { double[,] m = NoiseReduction_byDivision(matrix, percentileThreshold); // smooth and truncate m = ImageTools.WienerFilter(m, 7); //Briggs uses 17 m = MatrixTools.SubtractAndTruncate2Zero(m, 1.0); // make binary m = MatrixTools.ThresholdMatrix2RealBinary(m, binaryThreshold); //agaion smooth and truncate m = ImageTools.GaussianBlur_5cell(m); //m = ImageTools.GaussianBlur_5cell(m); //do a seoncd time //m = ImageTools.Blur(m, 10); // use a simple neighbourhood blurring function. double binaryThreshold2 = binaryThreshold * 0.8; m = MatrixTools.ThresholdMatrix2RealBinary(m, binaryThreshold2); return(m); }
private void simpleButton1_Click(object sender, EventArgs e) { using (var dlg = new OpenFileDialog()) { dlg.Title = "Open Image"; dlg.Filter = "Image Files(*.BMP;*.JPG;*.PNG)|*.BMP;*.JPG;*.PNG"; if (dlg.ShowDialog() == DialogResult.OK) { suspectPictureBox.Image = Image.FromFile(dlg.FileName); Image imgInput = Image.FromFile(dlg.FileName); Graphics gInput = Graphics.FromImage(imgInput); System.Drawing.Imaging.ImageFormat thisFormat = imgInput.RawFormat; SplashScreenManager.ShowForm(this, typeof(LoadingScreen), true, true, false, true); SplashScreenManager.Default.SetWaitFormCaption("Loading image..."); a.Add("Image", ImageTools.ImageToBase64(Image.FromFile(dlg.FileName), thisFormat)); SplashScreenManager.CloseForm(); suspectPictureBox.SizeMode = PictureBoxSizeMode.StretchImage; Controls.Add(suspectPictureBox); } } }
private async void ChangeBackground_OnClicked(object sender, RoutedEventArgs e) { var openPicker = new FileOpenPicker { ViewMode = PickerViewMode.Thumbnail, SuggestedStartLocation = PickerLocationId.PicturesLibrary }; openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".jpeg"); openPicker.FileTypeFilter.Add(".png"); openPicker.FileTypeFilter.Add(".gif"); StorageFile file = await openPicker.PickSingleFileAsync(); if (file == null) { return; } try { IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read); BitmapImage bitmapImage = new BitmapImage(); ImageBrush brush = new ImageBrush(); await bitmapImage.SetSourceAsync(stream); brush.ImageSource = bitmapImage; brush.Stretch = Stretch.None; App.RootFrame.Background = brush; var img = await ConvertImage.ConvertImagetoByte(file); await ImageTools.SaveWallpaper(img); } catch (Exception ex) { var msgDlg = new MessageDialog("Something went wrong settings the background. :-(."); msgDlg.ShowAsync(); } }
private void SetImage() { if (App.IsEnterprise()) { Source = "Camera"; } if (ImageTools.HasImage(location)) { if (ImageBaseHandler.current.isLocationCached(location.GetId())) { this.Source = ImageBaseHandler.current.GetLocationImageSource(location.GetId()); } else { this.Source = ImageTools.LoadImage(location); } } else { Source = "camera"; } }
public ActionResult Edit(SectionEditModel model, string action = nameof(ExperienceForSubmit.Save)) { SectionEntity res = null; if (ModelState.IsValid) { if (model.SectionImage != null && model.SectionImage.ContentLength > 0) { model.ImageId = ImageTools.SaveImage(model.SectionImage, FileArea.Section); } if (model.Id == 0 && model.OnTop && model.OverflowOnTop) { ModelState.AddModelError("", "Кол-во разделов в шапке привысило допустимый предел."); return(View(model)); } res = sectionService.Edit(model.MapFrom(model)); } if (res != null && res.Id > 0) { if (action == nameof(ExperienceForSubmit.Apply)) { return(RedirectToAction("Edit", new { id = res.Id })); } else { return(RedirectToAction("Index")); } } ModelState.AddModelError("", "Во время сохранения произошли ошибки"); return(View(model)); }
/// <summary> /// Resizes the image. /// </summary> /// <param name="url">The URL.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="preserverAspectRatio">The preserver aspect ratio.保持比例</param> /// <param name="quality">The quality.</param> /// <returns></returns> public virtual ActionResult ResizeImage(string url, int width, int height, bool?preserverAspectRatio, int?quality) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException(url); } url = HttpUtility.UrlDecode(url); var index = url.IndexOf("?"); if (index != -1) { url = url.Substring(0, index); } var imageFullPath = Server.MapPath(url); preserverAspectRatio = preserverAspectRatio ?? true; quality = quality ?? 80; var cachingPath = GetCachingFilePath(imageFullPath, width, height, preserverAspectRatio.Value, quality.Value); if (!System.IO.File.Exists(cachingPath)) { lock (resizeImageLocker) { if (!System.IO.File.Exists(cachingPath)) { var dir = Path.GetDirectoryName(cachingPath); IOUtility.EnsureDirectoryExists(dir); var success = ImageTools.ResizeImage(imageFullPath, cachingPath, width, height, preserverAspectRatio.Value, quality.Value); if (!success) { cachingPath = imageFullPath; } } } } SetCache(HttpContext.Response, 2592000, "*"); return(File(cachingPath, IOUtility.MimeType(imageFullPath))); }
public void GetDistinctColoursTest() { ReportStart(); _bitmap = RandomBitmap.Create(new Size(50, 50), 10, PixelFormat.Format32bppArgb); Collection <Color> expectedDistinctColours = new Collection <Color>(); Color c; for (int y = 0; y < _bitmap.Height; y++) { for (int x = 0; x < _bitmap.Width; x++) { c = _bitmap.GetPixel(x, y); if (expectedDistinctColours.Contains(c) == false) { expectedDistinctColours.Add(c); } } } Color[] actualColours = ImageTools.GetColours(_bitmap); Collection <Color> actualDistinctColours = ImageTools.GetDistinctColours(actualColours); Assert.AreEqual(expectedDistinctColours.Count, actualDistinctColours.Count); // NB we can't compare expected[i] to actual[i] as the two collections // are in different orders due to the use of Hashtable in the // GetDistinctColours method foreach (Color thisColour in expectedDistinctColours) { CollectionAssert.Contains(actualDistinctColours, thisColour, thisColour.ToString()); } ReportEnd(); }
/// <summary> /// AN EXPERIMENTAL SPECTROGRAM - A FALSE-COLOR VERSION OF A standard scale SPECTROGRAM. /// </summary> /// <param name="dbSpectrogramData">The original data for decibel spectrogram.</param> /// <param name="nrSpectrogram">The noise-reduced spectrogram.</param> /// <param name="sourceRecordingName">Name of the source file. Required only to add label to spectrogram.</param> /// <returns>Image of spectrogram.</returns> public static Image GetDecibelSpectrogram_Ridges(double[,] dbSpectrogramData, SpectrogramStandard nrSpectrogram, string sourceRecordingName) { // ########################### SOBEL ridge detection var ridgeThreshold = 3.5; var matrix = ImageTools.WienerFilter(dbSpectrogramData, 3); var hits = RidgeDetection.Sobel5X5RidgeDetectionExperiment(matrix, ridgeThreshold); // ########################### EIGEN ridge detection //double ridgeThreshold = 6.0; //double dominanceThreshold = 0.7; //var rotatedData = MatrixTools.MatrixRotate90Anticlockwise(dbSpectrogramData); //byte[,] hits = RidgeDetection.StructureTensorRidgeDetection(rotatedData, ridgeThreshold, dominanceThreshold); //hits = MatrixTools.MatrixRotate90Clockwise(hits); // ########################### EIGEN ridge detection var frameStep = nrSpectrogram.Configuration.WindowStep; var sampleRate = nrSpectrogram.SampleRate; var image = SpectrogramTools.CreateFalseColourDecibelSpectrogram(dbSpectrogramData, nrSpectrogram.Data, hits); image = BaseSonogram.GetImageAnnotatedWithLinearHertzScale(image, sampleRate, frameStep, $"AN EXPERIMENTAL DECIBEL SPECTROGRAM with ridges ({sourceRecordingName})"); //var image = decibelSpectrogram.GetImageFullyAnnotated("DECIBEL SPECTROGRAM - with ridges"); return(image); }
private void logoSelectBtn_Click(object sender, RoutedEventArgs e) { try { var dlg = new Microsoft.Win32.OpenFileDialog() { Filter = "png|*.png" }; if (dlg.ShowDialog(this) == true) { string logoPath = AppDomain.CurrentDomain.BaseDirectory + "logo.png"; this.txtLogoPath.Text = logoPath; File.Copy(dlg.FileName, logoPath, true); App.reportSettingModel.DefaultLogo = false; this.logoImg.Source = ImageTools.GetBitmapImage(logoPath); } } catch (Exception) { FileHelper.SetFolderPower(AppDomain.CurrentDomain.BaseDirectory, "Everyone", "FullControl"); FileHelper.SetFolderPower(AppDomain.CurrentDomain.BaseDirectory, "Users", "FullControl"); } }
public Field(List <Setting> settingList, Robot[] robots, Obstacle[] obstacles, double previousDamageDifference, double previousMaxDamageDifference, double previousTimeElapsed) : base(settingList) { ROBOTS = robots; OBSTACLES = obstacles; FIELD_SIZE = getFieldSize(base.settingPairs.field_size); base.GAME_OBJECT.GetComponent <Rigidbody>(); Vector3 fieldFootprint = GAME_OBJECT.GetComponent <BoxCollider>().bounds.size; Vector3 rescale = GAME_OBJECT.transform.localScale; rescale.x = (float)FIELD_SIZE.width; rescale.y = (float)FIELD_HEIGHT; rescale.z = (float)FIELD_SIZE.depth; GAME_OBJECT.transform.localScale = rescale; if (ROBOTS != null && OBSTACLES != null) { GAME_ENGINE = new GameEngine(this, ROBOTS, OBSTACLES, previousDamageDifference, previousMaxDamageDifference, previousTimeElapsed, base.settingPairs); } settingsOpen = false; base.GAME_OBJECT.GetComponent <MeshRenderer>().material.color = ImageTools.getColorFromString(base.settingPairs.field_color); base.colorScheme = ImageTools.getColorFromString(base.settingPairs.color_scheme); fieldColorString = base.settingPairs.field_color; base.GAME_OBJECT.GetComponent <MeshRenderer>().material.color = ImageTools.getColorFromString(fieldColorString); }
public async Task <int> AddChildAsync(RegisterViewModel child) { //TODO : Save images var employeeName = db.Employees.Include(e => e.City) .SingleOrDefault(e => e.EmployeeId == child.EmployeeId); string personalImageName = ImageTools.SavePersonalImage(child.PersonalImage, employeeName.FullName, child.FullName, employeeName.City.CityName); string reportCardImageName = ImageTools.SaveReportCardImage(child.ReportCardImage, employeeName.FullName, child.FullName, employeeName.City.CityName); var addChild = new Child() { FullName = child.FullName, NationalCode = child.NationalCode, GradeId = child.GradeId, EmployeeId = child.EmployeeId, Birthday = DateConvertor.ToMiladi(child.Birthday), Image = personalImageName, ReportCards = new List <ReportCard>() { new ReportCard() { AverageGrade = child.AverageGrade, ReportCardImage = reportCardImageName, IsConfirm = false, StatusId = 1, OptionalDetails = null, Description = "" } } }; await db.Children.AddAsync(addChild); await db.SaveChangesAsync(); return(addChild.ChildId); }
/// <summary> /// Can be used for visual checking and debugging purposes. /// </summary> public static void DrawNormalisedIndexMatrices(DirectoryInfo dir, string baseName, Dictionary <string, double[, ]> dictionary) { var list = new List <Image <Rgb24> >(); foreach (string key in ContentSignatures.IndexNames) { var bmp = ImageTools.DrawReversedMatrixWithoutNormalisation(dictionary[key]); // need to rotate spectrogram to get correct orientation. bmp.RotateFlip(RotateFlipType.Rotate270FlipNone); // draw grid lines and add axis scales var xAxisPixelDuration = TimeSpan.FromSeconds(60); var fullDuration = TimeSpan.FromTicks(xAxisPixelDuration.Ticks * bmp.Width); var freqScale = new FrequencyScale(11025, 512, 1000); SpectrogramTools.DrawGridLinesOnImage((Image <Rgb24>)bmp, TimeSpan.Zero, fullDuration, xAxisPixelDuration, freqScale); const int trackHeight = 20; var recordingStartDate = default(DateTimeOffset); var timeBmp = ImageTrack.DrawTimeTrack(fullDuration, recordingStartDate, bmp.Width, trackHeight); var image = ImageTools.CombineImagesVertically(bmp, timeBmp); // add a header to the spectrogram var header = Drawing.NewImage(image.Width, 20, Color.LightGray); header.Mutate(g => { g.DrawText(key, Drawing.Tahoma9, Color.Black, new PointF(4, 4)); list.Add(ImageTools.CombineImagesVertically(header, image)); }); } // save the image - the directory for the path must exist var path = Path.Combine(dir.FullName, baseName + "__Towsey.Acoustic.GreyScaleImages.png"); var indexImage = ImageTools.CombineImagesInLine(list); indexImage?.Save(path); }
private void fillInData(string id) { var appPath = Application.StartupPath; var constring = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + appPath + "\\CriminalRecord.mdf;Integrated Security=True;"; var con = new SqlConnection(constring); if (con.State != ConnectionState.Open) { con.Open(); } var sql = "SELECT * FROM Committed_Target WHERE Committed_Target_ID =" + id; var command = new SqlCommand(sql, con); var read = command.ExecuteReader(); while (read.Read()) { idTextBox.Text = read.GetInt32(0).ToString(); firstNameTextBox.Text = read.GetString(1); lastNameTextBox.Text = read.GetString(1); birthdayDatePicker.DateTime = read.GetDateTime(2); genderComboBox.Text = read.GetString(9); trialDayDatePicker.DateTime = read.GetDateTime(7); jailNumberTextBox.Text = read.GetString(6); buildTextBox.Text = read.GetString(10); foreach (DateTime crimes in fillinTextBox(id)) { crimesTextBox.Text = crimes.ToString(); } heightTextBox.Text = read.GetString(11); eyesTextBox.Text = read.GetString(12); hairTextBox.Text = read.GetString(13); image = read.GetString(14); suspectPictureBox.Image = ImageTools.Base64ToImage(read.GetString(14)); } con.Close(); }
public ActionResult SectionSettings(SectionsSettingsModel model) { var serviceModel = new SectionSettingsModel(); serviceModel.SettingsArea = SectionSettingArea.Settings; serviceModel.MaxAllowedSections = model.MaxAllowedSections; serviceModel.MaxAllowedSectionsOnTop = model.MaxAllowedSectionsOnTop; try { SectionSettingsService.RemoveDefaultSettings(); if (model.SectionImage != null && model.SectionImage.ContentLength > 0) { serviceModel.DefaultPictureId = ImageTools .SaveImage(model.SectionImage, model.FileArea, isDefault: true); } else { serviceModel.DefaultPictureId = model.DefaultPictureId; } } catch (Exception e) { ModelState.AddModelError("", "Во время сохранения изображения произошли ошибки"); } try { SectionSettingsService.Edit(serviceModel); } catch (Exception ex) { ModelState.AddModelError("", "Во время сохранения произошли ошибки"); } return(RedirectToAction("SectionSettings")); }
public void Load(string path) { var files = FindFiles(path); if (files == null) { return; } foreach (var file in files) { var svgDoc = SvgDocument.Open <SvgDocument>(file); var name = GetIconName(file); var normalizedName = GetIconNormalizedName(name); if (iconCollection.Exists(x => x.Pack == pack && x.Name == name) /*|| mappedIconCollection.Exists( x => x.Icons.Exists( i => i.Pack == pack && i.Name == name ) )*/) { continue; } using (var image = svgDoc.Draw(24, 24)) { var data = ImageTools.ImageToByteArray(image); iconCollection.Insert(new Icon { Pack = pack, Name = name, NormalizedName = normalizedName, Image = data, }); } } }
internal async Task <byte[]> GetQRPic(string uniacid, ObjectId accountID, string contentRootPath) { var account = GetModelByIDAndUniacID(accountID, uniacid); if (string.IsNullOrEmpty(account.AccountPhoneNumber) || string.IsNullOrEmpty(account.CarNumber)) { string no_qrPath = $@"{contentRootPath}/wwwroot/images/no_qr.jpg"; return(File.ReadAllBytes(no_qrPath)); } byte[] qrData; var bucket = new GridFSBucket(mongoDB); if (account.QRFileID != ObjectId.Empty) { return(await bucket.DownloadAsBytesAsync(account.QRFileID)); } string qrInfo = $@"{We7Config.SiteRoot}account/GetAccountInfo?uniacid={uniacid}&AccountID={account.AccountID}"; Bitmap qr = QRCodeHelper.Create(qrInfo, 300); Image qrRaw = ImageTools.ResizeImage(qr, 286, 286, 0); string bgPath = $@"{contentRootPath}/wwwroot/images/qr_bg.jpg"; Bitmap qrBit = ImageTools.CombinImage(new Bitmap(bgPath), qrRaw, 171, 128); MemoryStream ms = new MemoryStream(); qrBit.Save(ms, ImageFormat.Jpeg); qrData = ms.GetBuffer(); var options = new GridFSUploadOptions { Metadata = new BsonDocument { { "content-type", "Image/jpg" } } }; var id = await bucket.UploadFromBytesAsync($"qr_{accountID.ToString()}.jpg", qrData, options); collection.UpdateOne(x => x.AccountID.Equals(accountID) && x.uniacid.Equals(uniacid), Builders <AccountModel> .Update.Set(x => x.QRFileID, id)); return(qrData); }
public ActionResult Preview(string imagePath, string rotateTypes) { var physicalPath = Server.MapPath(HttpUtility.UrlDecode(imagePath)); var imageFormat = ImageTools.ConvertToImageFormat(Path.GetExtension(physicalPath)); Stream imageStream = new MemoryStream(); Stream outputStream = new MemoryStream(); try { imageStream = RotateImage(rotateTypes, physicalPath, imageFormat); ImageTools.ResizeImage(imageStream, outputStream, imageFormat, 0, 200, true, 80); outputStream.Position = 0; return(File(outputStream, IOUtility.MimeType(physicalPath))); } finally { if (imageStream != null) { imageStream.Close(); imageStream.Dispose(); } } }
public CubeHelix(string mode) { if (mode.Equals(ColorCubeHelix.Default)) { //Hsl colorARgb = new Hsl(300, 0.5, 0.0); //Hsl colorBRgb = new Hsl(-240, 0.5, 1.0); //Hsl colorARgb; //Hsl colorBRgb; //CubeHelix(colorARgb, colorBRgb); this.SetDefaultCubeHelix(); //string path = @"C:\SensorNetworks\Output\FalseColourSpectrograms\SpectrogramZoom\ZoomImages\testImage.png"; //TestImage(path); } else if (mode.Equals(ColorCubeHelix.Grayscale)) { this.ColourPallette = ImageTools.GrayScale(); } else if (mode.Equals(ColorCubeHelix.RedScale)) { this.SetRedScalePallette(); } else if (mode.Equals(ColorCubeHelix.CyanScale)) { this.SetCyanScalePallette(); } else { LoggedConsole.WriteErrorLine("WARNING: {0} is UNKNOWN COLOUR PALLETTE!", mode); } }
private void BoardButton_Click(object sender, RoutedEventArgs e) { string[] args = Environment.GetCommandLineArgs(); Image <Hsv, byte> img = new Image <Hsv, byte>(args[1]); Image <Gray, byte> blue = ImageTools.FilterColor(img, new Hsv(90, 90, 50), new Hsv(120, 255, 255)); Image <Gray, byte> green = ImageTools.FilterColor(img, new Hsv(35, 70, 35), new Hsv(90, 255, 255)); Image <Gray, byte> yellow = ImageTools.FilterColor(img, new Hsv(10, 70, 127), new Hsv(35, 255, 255)); Image <Gray, byte> red = ImageTools.FilterColor( img, new KeyValuePair <Hsv, Hsv>[] { new KeyValuePair <Hsv, Hsv>(new Hsv(0, 85, 80), new Hsv(12, 255, 255)), new KeyValuePair <Hsv, Hsv>(new Hsv(150, 85, 80), new Hsv(179, 255, 255)) } ); DetectionData ddb = ImageTools.DetectSquares(blue); DetectionData ddr = ImageTools.DetectSquares(red); DetectionData ddg = ImageTools.DetectSquares(green); DetectionData ddy = ImageTools.DetectSquares(yellow); ddb.RemoveNoises(); ddr.RemoveNoises(); ddg.RemoveNoises(); ddy.RemoveNoises(); ddb.AddColor(ddr); ddb.AddColor(ddg); ddb.AddColor(ddy); var board = ddb.CreateBoard(); var di = ddb.DrawDetection().Bitmap; MessageBox.Show("Detected board: " + board.Height + "x" + board.Width); ImageTools.ShowInNamedWindow(img.Convert <Bgr, byte>(), "Original"); }
public override void Generate() { int subjectIndex = 0; foreach (Subject s in this.subjectsToSketch) { if (subjectIndex >= this.subjectsToSketch.Count) { break; } Rectangle rect = this.specifiedSubjectSizes[subjectIndex++]; int finalWidth = rect.Width; int finalHeight = rect.Height; s.SketchedImage = ImageTools.ScaleBySize(s.SourceImage, finalWidth, finalHeight); s.sketchAtX = rect.X; s.sketchAtY = rect.Y; //Console.WriteLine("Final Image: " + rect.X + ", " + rect.Y + ", " + (rect.X + finalWidth) + ", " + (rect.Y + finalHeight)); this.subjectsSketched.Add(s); } }
public async Task <HttpResponseMessage> Upload() { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } List <string> files = new List <string>(); try { var root = HttpContext.Current.Server.MapPath("~/FileUploads"); var streamProvider = this.GetMultipartProvider(root); // Read the MIME multipart content using the stream provider we just created. await Request.Content.ReadAsMultipartAsync(streamProvider); foreach (MultipartFileData file in streamProvider.FileData) { //string medium = Path.Combine(root, "medium_" + Path.GetFileName(file.LocalFileName)); string medium = Path.Combine(root, "medium_" + Path.GetFileName(file.LocalFileName)); ImageTools.Resize(file.LocalFileName, medium, 190, 190, true); files.Add(file.LocalFileName); } // Send OK Response along with saved file names to the client. return(Request.CreateResponse(HttpStatusCode.OK, Path.GetFileName(files.First()))); } catch (Exception e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e)); } }
private Image <Bgr, byte> Filter(Image <Bgr, byte> sourceImg, bool debugMode = false) { Image <Hsv, byte> img = sourceImg.Convert <Hsv, byte>(); Image <Gray, byte> blue = ImageTools.FilterColor(img, new Hsv(90, 90, 50), new Hsv(120, 255, 255), debugMode ? "Blue Debug Window" : ""); Image <Gray, byte> green = ImageTools.FilterColor(img, new Hsv(35, 70, 35), new Hsv(90, 255, 255), debugMode ? "Green Debug Window" : ""); Image <Gray, byte> yellow = ImageTools.FilterColor(img, new Hsv(10, 70, 127), new Hsv(35, 255, 255), debugMode ? "Yellow Debug Window" : ""); Image <Gray, byte> red = ImageTools.FilterColor( img, new KeyValuePair <Hsv, Hsv>[] { new KeyValuePair <Hsv, Hsv>(new Hsv(0, 85, 80), new Hsv(12, 255, 255)), new KeyValuePair <Hsv, Hsv>(new Hsv(150, 85, 80), new Hsv(179, 255, 255)) }, debugMode ? "Red Debug Window" : "" ); var colorDetection = ImageTools.CombineMaps(new List <KeyValuePair <Image <Gray, byte>, Bgr> > { new KeyValuePair <Image <Gray, byte>, Bgr>(blue, ImageTools.Colors.Blue), new KeyValuePair <Image <Gray, byte>, Bgr>(red, ImageTools.Colors.Red), new KeyValuePair <Image <Gray, byte>, Bgr>(green, ImageTools.Colors.Green), new KeyValuePair <Image <Gray, byte>, Bgr>(yellow, ImageTools.Colors.Yellow), }); return(colorDetection); }
/// <summary> /// This method assumes that the height of the passed sonogram image is half of the original frame size. /// This assumption allows the frequency scale grid lines to be placed at the correct intervals. /// </summary> public static Image <Rgb24> FrameSonogram( Image <Rgb24> sonogramImage, Image <Rgb24> titleBar, TimeSpan minuteOffset, TimeSpan xAxisTicInterval, TimeSpan xAxisPixelDuration, TimeSpan labelInterval, int nyquist, int hertzInterval) { double secondsDuration = xAxisPixelDuration.TotalSeconds * sonogramImage.Width; var fullDuration = TimeSpan.FromSeconds(secondsDuration); // init frequency scale int frameSize = sonogramImage.Height * 2; var freqScale = new FrequencyScale(nyquist, frameSize, hertzInterval); SpectrogramTools.DrawGridLinesOnImage((Image <Rgb24>)sonogramImage, minuteOffset, fullDuration, xAxisTicInterval, freqScale); int imageWidth = sonogramImage.Width; var timeBmp = ImageTrack.DrawShortTimeTrack(minuteOffset, xAxisPixelDuration, xAxisTicInterval, labelInterval, imageWidth, "Seconds"); return(ImageTools.CombineImagesVertically(titleBar, timeBmp, sonogramImage, timeBmp)); }
public void Refresh() { location = DatabaseHandler.GetDatabase().GetLocation(id); //set title this.Title = location.GetName(); //set proportions this.imageFrame.HeightRequest = MasterNavigationPage.current.Height / 2.0; //init image if (ImageTools.HasImage(location)) { if (ImageBaseHandler.current.isLocationCached(location.GetId())) { SetImage(ImageBaseHandler.current.GetLocationImageSource(location.GetId())); } else { SetImage(ImageTools.LoadImage(location)); } } else //if no image give it the place holder image { SetImage("camera"); } //set colors this.BackgroundColor = PageColors.secondaryColor; }
/// <summary> /// Experiments with false colour images - discretising the colours /// SEEMED LIKE A GOOD IDEA AT THE TIME! /// Not sure it is any use but worthwhile preserving the code. /// </summary> public static void DiscreteColourSpectrograms() { Console.WriteLine("Reading image"); //string wavFilePath = @"C:\SensorNetworks\WavFiles\LewinsRail\BAC2_20071008-085040.wav"; //string inputPath = @"C:\SensorNetworks\Output\FalseColourSpectrograms\7a667c05-825e-4870-bc4b-9cec98024f5a_101013-0000.colSpectrum.png"; //string outputPath = @"C:\SensorNetworks\Output\FalseColourSpectrograms\7a667c05-825e-4870-bc4b-9cec98024f5a_101013-0000.discreteColSpectrum.png"; string inputPath = @"C:\SensorNetworks\Output\FalseColourSpectrograms\DM420036.colSpectrum.png"; string outputPath = @"C:\SensorNetworks\Output\FalseColourSpectrograms\DM420036.discreteColSpectrum.png"; const int R = 0; const int G = 1; const int B = 2; double[,] discreteIndices = new double[12, 3]; // Ht, ACI and Ampl values in 0,1 #pragma warning disable SA1107 // Code should not contain multiple statements on one line discreteIndices[0, R] = 0.00; discreteIndices[0, G] = 0.00; discreteIndices[0, B] = 0.00; // white discreteIndices[1, R] = 0.20; discreteIndices[1, G] = 0.00; discreteIndices[1, B] = 0.00; // pale blue discreteIndices[2, R] = 0.60; discreteIndices[2, G] = 0.20; discreteIndices[2, B] = 0.10; // medium blue discreteIndices[3, R] = 0.00; discreteIndices[3, G] = 0.00; discreteIndices[3, B] = 0.40; // pale yellow discreteIndices[4, R] = 0.00; discreteIndices[4, G] = 0.05; discreteIndices[4, B] = 0.70; // bright yellow discreteIndices[5, R] = 0.20; discreteIndices[5, G] = 0.05; discreteIndices[5, B] = 0.80; // yellow/green discreteIndices[6, R] = 0.50; discreteIndices[6, G] = 0.05; discreteIndices[6, B] = 0.50; // yellow/green discreteIndices[7, R] = 0.99; discreteIndices[7, G] = 0.30; discreteIndices[7, B] = 0.70; // green discreteIndices[8, R] = 0.10; discreteIndices[8, G] = 0.95; discreteIndices[8, B] = 0.10; // light magenta discreteIndices[9, R] = 0.50; discreteIndices[9, G] = 0.95; discreteIndices[9, B] = 0.50; // medium magenta discreteIndices[10, R] = 0.70; discreteIndices[10, G] = 0.95; discreteIndices[10, B] = 0.70; // dark magenta discreteIndices[11, R] = 0.95; discreteIndices[11, G] = 0.95; discreteIndices[11, B] = 0.95; // black #pragma warning restore SA1107 // Code should not contain multiple statements on one line int N = 12; // number of discrete colours byte[,] discreteColourValues = new byte[N, 3]; // Ht, ACI and Ampl values in 0,255 for (int r = 0; r < discreteColourValues.GetLength(0); r++) { for (int c = 0; c < discreteColourValues.GetLength(1); c++) { discreteColourValues[r, c] = (byte)Math.Floor((1 - discreteIndices[r, c]) * 255); } } // set up the colour pallette. Color[] colourPalette = new Color[N]; //palette for (int c = 0; c < N; c++) { colourPalette[c] = Color.FromArgb(discreteColourValues[c, R], discreteColourValues[c, G], discreteColourValues[c, B]); } // read in the image Bitmap image = ImageTools.ReadImage2Bitmap(inputPath); for (int x = 0; x < image.Width; x++) { for (int y = 0; y < image.Height; y++) { Color imageCol = image.GetPixel(x, y); byte[] imageColorVector = new byte[3]; imageColorVector[0] = imageCol.R; imageColorVector[1] = imageCol.G; imageColorVector[2] = imageCol.B; // get colour from palette closest to the existing colour double[] distance = new double[N]; for (int c = 0; c < N; c++) { byte[] colourVector = new byte[3]; colourVector[0] = discreteColourValues[c, 0]; colourVector[1] = discreteColourValues[c, 1]; colourVector[2] = discreteColourValues[c, 2]; distance[c] = DataTools.EuclideanDistance(imageColorVector, colourVector); } int minindex, maxindex; double min, max; DataTools.MinMax(distance, out minindex, out maxindex, out min, out max); //if ((col.R > 200) && (col.G > 200) && (col.B > 200)) image.SetPixel(x, y, colourPalette[minindex]); } } ImageTools.WriteBitmap2File(image, outputPath); }
/// <summary> /// This method draws a spectrogram with other useful information attached. /// </summary> /// <param name="sonogram">of BaseSonogram class.</param> /// <param name="events">a list of acoustic events.</param> /// <param name="plots">a list of plots relevant to the spectrogram scores.</param> /// <param name="hits">not often used - can be null.</param> public static Image <Rgb24> GetSonogramPlusCharts( BaseSonogram sonogram, List <AcousticEvent> events, List <Plot> plots, double[,] hits) { var spectrogram = sonogram.GetImage(doHighlightSubband: false, add1KHzLines: true, doMelScale: false); Contract.RequiresNotNull(spectrogram, nameof(spectrogram)); var height = spectrogram.Height; var frameSize = sonogram.Configuration.WindowSize; // init with linear frequency scale and draw freq grid lines on image int hertzInterval = 1000; if (height < 200) { hertzInterval = 2000; } var freqScale = new FrequencyScale(sonogram.NyquistFrequency, frameSize, hertzInterval); FrequencyScale.DrawFrequencyLinesOnImage(spectrogram, freqScale.GridLineLocations, includeLabels: true); // draw event outlines onto spectrogram. if (events != null && events.Count > 0) { // set colour for the events foreach (AcousticEvent ev in events) { ev.BorderColour = AcousticEvent.DefaultBorderColor; ev.ScoreColour = AcousticEvent.DefaultScoreColor; ev.DrawEvent(spectrogram, sonogram.FramesPerSecond, sonogram.FBinWidth, height); } } // now add in hits to the spectrogram image. if (hits != null) { spectrogram = Image_MultiTrack.OverlayScoresAsRedTransparency(spectrogram, hits); // following line needs to be reworked if want to call OverlayRainbowTransparency(hits); //image.OverlayRainbowTransparency(hits); } int pixelWidth = spectrogram.Width; var titleBar = LDSpectrogramRGB.DrawTitleBarOfGrayScaleSpectrogram("TITLE", pixelWidth); var timeTrack = ImageTrack.DrawTimeTrack(sonogram.Duration, pixelWidth); var imageList = new List <Image <Rgb24> > { titleBar, timeTrack, spectrogram, timeTrack, }; if (plots != null) { foreach (var plot in plots) { // Next line assumes plot data normalised in 0,1 var plotImage = plot.DrawAnnotatedPlot(ImageTrack.DefaultHeight); // the following draws same plot without the title. //var plotImage = ImageTrack.DrawScoreArrayTrack(plot.data, plot.threshold, pixelWidth); imageList.Add(plotImage); } } var compositeImage = ImageTools.CombineImagesVertically(imageList); return(compositeImage); }
public void Execute(Arguments arguments) { LoggedConsole.WriteLine("feature learning process..."); var inputDir = @"D:\Mahnoosh\Liz\Least_Bittern\"; var inputPath = Path.Combine(inputDir, "TrainSet\\one_min_recordings"); var trainSetPath = Path.Combine(inputDir, "TrainSet\\train_data"); // var testSetPath = Path.Combine(inputDir, "TestSet"); var configPath = @"D:\Mahnoosh\Liz\Least_Bittern\FeatureLearningConfig.yml"; var resultDir = Path.Combine(inputDir, "FeatureLearning"); Directory.CreateDirectory(resultDir); // var outputMelImagePath = Path.Combine(resultDir, "MelScaleSpectrogram.png"); // var outputNormMelImagePath = Path.Combine(resultDir, "NormalizedMelScaleSpectrogram.png"); // var outputNoiseReducedMelImagePath = Path.Combine(resultDir, "NoiseReducedMelSpectrogram.png"); // var outputReSpecImagePath = Path.Combine(resultDir, "ReconstrcutedSpectrogram.png"); // var outputClusterImagePath = Path.Combine(resultDir, "Clusters.bmp"); // +++++++++++++++++++++++++++++++++++++++++++++++++patch sampling from 1-min recordings var configFile = configPath.ToFileInfo(); if (configFile == null) { throw new FileNotFoundException("No config file argument provided"); } else if (!configFile.Exists) { throw new ArgumentException($"Config file {configFile.FullName} not found"); } var configuration = ConfigFile.Deserialize <FeatureLearningSettings>(configFile); int patchWidth = (configuration.MaxFreqBin - configuration.MinFreqBin + 1) / configuration.NumFreqBand; var clusteringOutputList = FeatureLearning.UnsupervisedFeatureLearning(configuration, inputPath); List <double[][]> allBandsCentroids = new List <double[][]>(); for (int i = 0; i < clusteringOutputList.Count; i++) { var clusteringOutput = clusteringOutputList[i]; // writing centroids to a csv file // note that Csv.WriteToCsv can't write data types like dictionary<int, double[]> (problems with arrays) // I converted the dictionary values to a matrix and used the Csv.WriteMatrixToCsv // it might be a better way to do this string pathToClusterCsvFile = Path.Combine(resultDir, "ClusterCentroids" + i.ToString() + ".csv"); var clusterCentroids = clusteringOutput.ClusterIdCentroid.Values.ToArray(); Csv.WriteMatrixToCsv(pathToClusterCsvFile.ToFileInfo(), clusterCentroids.ToMatrix()); // sorting clusters based on size and output it to a csv file Dictionary <int, double> clusterIdSize = clusteringOutput.ClusterIdSize; int[] sortOrder = KmeansClustering.SortClustersBasedOnSize(clusterIdSize); // Write cluster ID and size to a CSV file string pathToClusterSizeCsvFile = Path.Combine(resultDir, "ClusterSize" + i.ToString() + ".csv"); Csv.WriteToCsv(pathToClusterSizeCsvFile.ToFileInfo(), clusterIdSize); // Draw cluster image directly from clustering output List <KeyValuePair <int, double[]> > list = clusteringOutput.ClusterIdCentroid.ToList(); double[][] centroids = new double[list.Count][]; for (int j = 0; j < list.Count; j++) { centroids[j] = list[j].Value; } allBandsCentroids.Add(centroids); List <double[, ]> allCentroids = new List <double[, ]>(); for (int k = 0; k < centroids.Length; k++) { // convert each centroid to a matrix in order of cluster ID // double[,] cent = PatchSampling.ArrayToMatrixByColumn(centroids[i], patchWidth, patchHeight); // OR: in order of cluster size double[,] cent = MatrixTools.ArrayToMatrixByColumn(centroids[sortOrder[k]], patchWidth, configuration.PatchHeight); // normalize each centroid double[,] normCent = DataTools.normalise(cent); // add a row of zero to each centroid double[,] cent2 = PatchSampling.AddRow(normCent); allCentroids.Add(cent2); } // concatenate all centroids double[,] mergedCentroidMatrix = PatchSampling.ListOf2DArrayToOne2DArray(allCentroids); // Draw clusters var clusterImage = ImageTools.DrawMatrixWithoutNormalisation(mergedCentroidMatrix); clusterImage.RotateFlip(RotateFlipType.Rotate270FlipNone); var outputClusteringImage = Path.Combine(resultDir, "ClustersWithGrid" + i.ToString() + ".bmp"); clusterImage.Save(outputClusteringImage); } // extracting features FeatureExtraction.UnsupervisedFeatureExtraction(configuration, allBandsCentroids, trainSetPath, resultDir); LoggedConsole.WriteLine("Done..."); }
/// <summary> /// Converts summary indices to a tracks image, one track for each index. /// </summary> public static Image <Rgb24> DrawImageOfSummaryIndices( Dictionary <string, IndexProperties> listOfIndexProperties, Dictionary <string, double[]> dictionaryOfSummaryIndices, string titleText, TimeSpan indexCalculationDuration, DateTimeOffset?recordingStartDate, List <GapsAndJoins> errors = null, bool verbose = true) { const int trackHeight = DefaultTrackHeight; int scaleLength = 0; var backgroundColour = Color.White; // init list of bitmap images to store image tracks var bitmapList = new List <Tuple <IndexProperties, Image <Rgb24> > >(dictionaryOfSummaryIndices.Keys.Count); // set up strings to store info about which indices are used var s1 = new StringBuilder("Indices not found:"); var s2 = new StringBuilder("Indices not plotted:"); // accumulate the individual tracks in a List foreach (string key in dictionaryOfSummaryIndices.Keys) { if (!listOfIndexProperties.ContainsKey(key)) { s1.Append(" {0},".Format2(key)); continue; } IndexProperties ip = listOfIndexProperties[key]; if (!ip.DoDisplay) { s2.Append(" {0},".Format2(key)); continue; } //string name = ip.Name; double[] array = dictionaryOfSummaryIndices[key]; scaleLength = array.Length; // alternate rows have different colour to make tracks easier to read backgroundColour = backgroundColour == Color.LightGray ? Color.White : Color.LightGray; var bitmap = ip.GetPlotImage(array, backgroundColour, errors); bitmapList.Add(Tuple.Create(ip, bitmap)); } if (verbose) { Logger.Warn(s1.ToString()); Logger.Warn(s2.ToString()); } var listOfBitmaps = bitmapList // .OrderBy(tuple => tuple.Item1.Order) // don't order because want to preserve alternating gray/white rows. .Select(tuple => tuple.Item2) .Where(b => b != null).ToList(); //set up the composite image parameters int x_offset = 2; int graphWidth = x_offset + scaleLength; int imageWidth = x_offset + scaleLength + TrackEndPanelWidth; Image <Rgb24> titleBmp = ImageTrack.DrawTitleTrack(imageWidth, trackHeight, titleText); TimeSpan xAxisPixelDuration = indexCalculationDuration; TimeSpan fullDuration = TimeSpan.FromTicks(xAxisPixelDuration.Ticks * graphWidth); Image <Rgb24> timeBmp1 = ImageTrack.DrawTimeRelativeTrack(fullDuration, graphWidth, trackHeight); Image <Rgb24> timeBmp2 = timeBmp1; DateTimeOffset?dateTimeOffset = recordingStartDate; if (dateTimeOffset.HasValue) { // draw extra time scale with absolute start time. AND THEN Do SOMETHING WITH IT. timeBmp2 = ImageTrack.DrawTimeTrack(fullDuration, dateTimeOffset, graphWidth, trackHeight); } //draw the composite bitmap var imageList = new List <Image <Rgb24> > { titleBmp, timeBmp1, }; foreach (var image in listOfBitmaps) { imageList.Add(image); } imageList.Add(timeBmp2); var compositeBmp = (Image <Rgb24>)ImageTools.CombineImagesVertically(imageList); return(compositeBmp); }
public override void SendResponse(System.Web.HttpResponse response) { int iErrorNumber = 0; string sFileName = ""; string sUnsafeFileName = ""; try { this.CheckConnector(); this.CheckRequest(); if (!this.CurrentFolder.CheckAcl(AccessControlRules.FileUpload)) { ConnectorException.Throw(Errors.Unauthorized); } HttpPostedFile oFile = HttpContext.Current.Request.Files[HttpContext.Current.Request.Files.AllKeys[0]]; if (oFile != null) { sUnsafeFileName = System.IO.Path.GetFileName(oFile.FileName); sFileName = Regex.Replace(sUnsafeFileName, @"[\:\*\?\|\/]", "_", RegexOptions.None); if (sFileName != sUnsafeFileName) { iErrorNumber = Errors.UploadedInvalidNameRenamed; } if (Connector.CheckFileName(sFileName) && !Config.Current.CheckIsHiddenFile(sFileName)) { // Replace dots in the name with underscores (only one dot can be there... security issue). if (Config.Current.ForceSingleExtension) { sFileName = Regex.Replace(sFileName, @"\.(?![^.]*$)", "_", RegexOptions.None); } if (!Config.Current.CheckSizeAfterScaling && this.CurrentFolder.ResourceTypeInfo.MaxSize > 0 && oFile.ContentLength > this.CurrentFolder.ResourceTypeInfo.MaxSize) { ConnectorException.Throw(Errors.UploadedTooBig); } string sExtension = System.IO.Path.GetExtension(oFile.FileName); sExtension = sExtension.TrimStart('.'); if (!this.CurrentFolder.ResourceTypeInfo.CheckExtension(sExtension)) { ConnectorException.Throw(Errors.InvalidExtension); } if (Config.Current.CheckIsNonHtmlExtension(sExtension) && !this.CheckNonHtmlFile(oFile)) { ConnectorException.Throw(Errors.UploadedWrongHtmlFile); } // Map the virtual path to the local server path. string sServerDir = this.CurrentFolder.ServerPath; string sFileNameNoExt = System.IO.Path.GetFileNameWithoutExtension(sFileName); int iCounter = 0; while (true) { string sFilePath = System.IO.Path.Combine(sServerDir, sFileName); if (System.IO.File.Exists(sFilePath)) { iCounter++; sFileName = sFileNameNoExt + "(" + iCounter + ")" + System.IO.Path.GetExtension(oFile.FileName); iErrorNumber = Errors.UploadedFileRenamed; } else { oFile.SaveAs(sFilePath); if (Config.Current.SecureImageUploads && ImageTools.IsImageExtension(sExtension) && !ImageTools.ValidateImage(sFilePath)) { System.IO.File.Delete(sFilePath); ConnectorException.Throw(Errors.UploadedCorrupt); } Settings.Images imagesSettings = Config.Current.Images; if (imagesSettings.MaxHeight > 0 && imagesSettings.MaxWidth > 0) { ImageTools.ResizeImage(sFilePath, sFilePath, imagesSettings.MaxWidth, imagesSettings.MaxHeight, true, imagesSettings.Quality); if (Config.Current.CheckSizeAfterScaling && this.CurrentFolder.ResourceTypeInfo.MaxSize > 0) { long fileSize = new System.IO.FileInfo(sFilePath).Length; if (fileSize > this.CurrentFolder.ResourceTypeInfo.MaxSize) { System.IO.File.Delete(sFilePath); ConnectorException.Throw(Errors.UploadedTooBig); } } } break; } } } else { ConnectorException.Throw(Errors.InvalidName); } } else { ConnectorException.Throw(Errors.UploadedCorrupt); } } catch (ConnectorException connectorException) { iErrorNumber = connectorException.Number; } catch (System.Security.SecurityException) { #if DEBUG throw; #else iErrorNumber = Errors.AccessDenied; #endif } catch (System.UnauthorizedAccessException) { #if DEBUG throw; #else iErrorNumber = Errors.AccessDenied; #endif } catch { #if DEBUG throw; #else iErrorNumber = Errors.Unknown; #endif } #if DEBUG if (iErrorNumber == Errors.None || iErrorNumber == Errors.UploadedFileRenamed || iErrorNumber == Errors.UploadedInvalidNameRenamed) { response.Clear(); } #else response.Clear(); #endif response.Write("<script type=\"text/javascript\">"); response.Write(this.GetJavaScriptCode(iErrorNumber, sFileName, this.CurrentFolder.Url + sFileName)); response.Write("</script>"); response.End(); }
/// <summary> /// Resizes the image. /// </summary> /// <param name="url">The URL.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="preserverAspectRatio">The preserver aspect ratio.保持比例</param> /// <param name="quality">The quality.</param> /// <returns></returns> public virtual ActionResult ResizeImage(string url, int width, int height, bool?preserverAspectRatio, int?quality) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException(url); } if (!ImageTools.IsImageExtension(Path.GetExtension(url))) { throw new HttpException(403, ""); } url = HttpUtility.UrlDecode(url); var index = url.IndexOf("?"); if (index != -1) { url = url.Substring(0, index); } preserverAspectRatio = preserverAspectRatio ?? true; quality = quality ?? 80; if (url.StartsWith("http://") || url.StartsWith("https://")) { //now no image cache for azure blob var provider = Kooboo.CMS.Content.Persistence.Providers.DefaultProviderFactory.GetProvider <Kooboo.CMS.Content.Persistence.IMediaContentProvider>(); var mediaContent = new MediaContent() { VirtualPath = url }; var data = provider.GetContentStream(mediaContent); if (data != null) { using (var imageStream = new MemoryStream(data)) { var imageFormat = ImageTools.ConvertToImageFormat(Path.GetExtension(mediaContent.VirtualPath)); Stream outStream = new MemoryStream(); ImageTools.ResizeImage(imageStream, outStream, imageFormat, width, height, preserverAspectRatio.Value, quality.Value); outStream.Position = 0; return(File(outStream, IOUtility.MimeType(url))); } } else { return(null); } } else { var imageFullPath = Server.MapPath(url); var cachingPath = GetCachingFilePath(imageFullPath, width, height, preserverAspectRatio.Value, quality.Value); if (!System.IO.File.Exists(cachingPath)) { if (!System.IO.File.Exists(cachingPath)) { var dir = Path.GetDirectoryName(cachingPath); IOUtility.EnsureDirectoryExists(dir); var success = ImageTools.ResizeImage(imageFullPath, cachingPath, width, height, preserverAspectRatio.Value, quality.Value); if (!success) { cachingPath = imageFullPath; } } } SetCache(HttpContext.Response, 2592000, "*"); return(File(cachingPath, IOUtility.MimeType(imageFullPath))); } }
public ImageWrapper(string fileName, ImageTools imgTools) { imageTools = imgTools; file = fileName; string[] dirs = file.Replace(@"\","/").Split('/'); name = dirs[dirs.Length - 1]; }
public SubDirectoryWrapper(string dir, string defaultFolderImage, ImageTools imgTools) { directory = dir; defaultImage = defaultFolderImage; imageTools = imgTools; string[] dirs = directory.Replace(@"\","/").Split('/'); name = dirs[dirs.Length - 1]; }
void saveImage(ImageTools.Image image, String filename, int num) { // get a path to save pictures String myPictures = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // create a new directory at that path DirectoryInfo lapseDir = Directory.CreateDirectory(myPictures + "\\" + filename + "\\" + camera.FriendlyName); // save the picture using (Stream stream = File.Create(lapseDir.FullName + "\\" + filename + num + ".jpg")) { // Declare jpeg encoder var encoder = new JpegEncoder(); // Set the image quality encoder.Quality = 90; // Finally encode raw bitmap and save it as a jpg image encoder.Encode(image, stream); // Close the stream stream.Close(); } }
private void lnkSaveUpdate_Click(object sender, System.EventArgs e) { Save(); ImageTools it = new ImageTools(this); string path = it.GetPath(it.cfg.PictureVirtualDirectory); CacheUpdater CacheUpd = new CacheUpdater(path, it); System.Threading.Thread WorkThread = new System.Threading.Thread( new System.Threading.ThreadStart(CacheUpd.UpdateAll)); // WorkThread.IsBackground = true; WorkThread.Start(); RedirectBack(); }
private void Save() { // Save Configuration. ImageBrowserConfig cfg = (ImageBrowserConfig)ReadConfig(typeof(ImageBrowserConfig)); if (cfg == null) { cfg = new ImageBrowserConfig(); } cfg.PictureVirtualDirectory = txtPictureVirtualDirectory.Text; cfg.ThumbnailCols = Convert.ToInt32(txtThumbnailCols.Text); cfg.ThumbnailRows = Convert.ToInt32(txtThumbnailRows.Text); cfg.PreviewCfg.MaxSize = Convert.ToInt32(txtPreviewMax.Text); cfg.PreviewCfg.JpegQuality = Convert.ToByte(txtPreviewJpegQuality.Text); cfg.ThumbCfg.MaxSize = Convert.ToInt32(txtThumbnailMax.Text); cfg.ThumbCfg.JpegQuality = Convert.ToByte(txtThumbJpegQuality.Text); cfg.PreviewCfg.Shadow = chkPreviewShadow.Checked; cfg.PreviewCfg.ShadowWidth = Convert.ToInt32(txtPvShadowWidth.Text); cfg.PreviewCfg.ShadowTransparency = Convert.ToDouble(txtPvShadowTrans.Text) / 100; cfg.PreviewCfg.BackgroundColor = PvBgColor.SelectedColor.ToArgb(); cfg.PreviewCfg.ShadowColor = PvShColor.SelectedColor.ToArgb(); cfg.PreviewCfg.BorderColor = PvBColor.SelectedColor.ToArgb(); cfg.PreviewCfg.SoftShadow = chkPvSoftShadow.Checked; cfg.ThumbCfg.Shadow = chkThumbnailShadow.Checked; cfg.ThumbCfg.ShadowWidth = Convert.ToInt32(txtTnShadowWidth.Text); cfg.ThumbCfg.BorderWidth = Convert.ToInt32(txtTnBorderWidth.Text); cfg.ThumbCfg.ShadowTransparency = Convert.ToDouble(txtTnShadowTrans.Text) / 100; cfg.ThumbCfg.BackgroundColor = TnBgColor.SelectedColor.ToArgb(); cfg.ThumbCfg.ShadowColor = TnShColor.SelectedColor.ToArgb(); cfg.ThumbCfg.BorderColor = TnBColor.SelectedColor.ToArgb(); cfg.ThumbCfg.SoftShadow = chkTnSoftShadow.Checked; WriteConfig(cfg); // Build shadow files. ImageTools it = new ImageTools(this); it.CreateShadowParts(cfg.PreviewCfg, cfg.ShadowPath); }