/// <summary> /// Handles the Click event of the btnUpload control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> protected void btnUpload_Click(object sender, EventArgs e) { try { HttpPostedFile file = fuFile.PostedFile; fuFile.Dispose(); if (!IsValidFileType(Path.GetExtension(file.FileName))) { throw new ArgumentOutOfRangeException("file", "File is not of valid type."); } if (file.ContentLength > 0) { FileWriter fileWriter = new FileWriter(); string finalPath = HttpContext.Current.Server.MapPath(path) + fuFile.FileName; fileWriter.Write(finalPath, file.InputStream); if (SiteSettings.GenerateThumbs) { ImageProcess.ResizeAndSave(fuFile.FileContent, fuFile.FileName, HttpContext.Current.Server.MapPath(PRODUCT_IMAGE_THUMB_PATH), SiteSettings.ThumbSmallWidth, SiteSettings.ThumbSmallHeight); } LoadImageList(); Master.MessageCenter.DisplaySuccessMessage(LocalizationUtility.GetText("lblImageSaved")); } } catch (Exception ex) { Logger.Error(typeof(imageselector).Name + ".btnUpload_Click", ex); Master.MessageCenter.DisplayCriticalMessage(ex.Message); } }
public static object GetData(string format, byte[] data) { return(format switch { "Bitmap" => ImageProcess.ToBitmap(data), _ => ByteHelper.ByteArray2Object(data) });
public VieModel_ImageViewer(string movieid) { DetailMovie models = DataBase.SelectDetailMovieById(movieid); //扫描目录 List <string> imagePathList = new List <string>(); try { foreach (var path in Directory.GetFiles(GlobalVariable.BasePicPath + $"ExtraPic\\{models.id}\\")) { imagePathList.Add(path); } } catch (Exception e) { Logger.LogE(e); } if (imagePathList.Count > 0) { imagePathList = imagePathList.CustomSort().ToList(); } DetailMovie = new DetailMovie(); if (models != null) { foreach (var path in imagePathList) { models.extraimagelist.Add(ImageProcess.GetExtraImage(path)); //加载预览图 } DetailMovie = models; } }
static void Main(string[] args) { string sourcePath = Path.Combine(Environment.CurrentDirectory, "images"); string destinationPath = Path.Combine(Environment.CurrentDirectory, "output"); ImageProcess imageProcess = new ImageProcess(); ImageProcessAsync imageProcessAsync = new ImageProcessAsync(); //先清除原本資料夾得內容 imageProcess.Clean(destinationPath); Stopwatch sw = new Stopwatch(); sw.Start(); imageProcess.ResizeImages(sourcePath, destinationPath, 2.0); sw.Stop(); var timeSync = sw.ElapsedMilliseconds; Console.WriteLine($"同步版時間: {sw.ElapsedMilliseconds} ms"); sw.Reset(); imageProcessAsync.Clean(destinationPath); sw.Start(); imageProcessAsync.ResizeImages(sourcePath, destinationPath, 2.0).Wait(); sw.Stop(); var timeAsync = sw.ElapsedMilliseconds; Console.WriteLine($"非同步版時間: {sw.ElapsedMilliseconds} ms"); var comparison = ((double)(timeSync - timeAsync) / timeSync) * 100; Console.WriteLine($"節省: {comparison:N2} % 時間"); Console.ReadLine(); }
public async Task <string> AnalyzeImageProcessAsync(VideoCamera videoCamera, ImageProcess imageProcess, AnalyzeRequest analyzeRequest) { var connectionApiData = new ConnectionApiData { Location = analyzeRequest.Location, SubscriptionKey = analyzeRequest.SubscriptionKey }; Languages enumLanguages = (Languages)analyzeRequest.IdLanguages; RequestType enumRequestTypes = (RequestType)analyzeRequest.TypeCode; switch (enumRequestTypes) { case RequestType.SceneChange: return(string.Empty); case RequestType.Face: return(await AnalyzeFace(imageProcess.ImageFile, videoCamera.IdPersonGroupsAPI, connectionApiData)); case RequestType.Carplate: return(await AnalyzeCarPlate(enumLanguages.ToString(), imageProcess.ImageFile, connectionApiData)); case RequestType.ImageDescription: return(await AnalyzeImageDescription(enumLanguages.ToString(), imageProcess.ImageFile, connectionApiData)); } return(null); }
private static Bitmap SaveFile(ImageFile imageFile) { var process = new ImageProcess(); object filterProperty = "Convert"; // ReSharper disable once UseIndexedProperty var convertFilterID = process.FilterInfos.get_Item(ref filterProperty).FilterID; // ReSharper disable once RedundantArgumentDefaultValue process.Filters.Add(convertFilterID, 0); object formatPropValue = FormatID.wiaFormatTIFF; object formatIdProperty = "FormatID"; object qualityPropValue = 100L; object qualityIdProperty = "Quality"; var properties = process.Filters[process.Filters.Count].Properties; // ReSharper disable once UseIndexedProperty var property = properties.get_Item(ref formatIdProperty); // ReSharper disable once UseIndexedProperty property.set_Value(ref formatPropValue); // ReSharper disable once UseIndexedProperty var qualityProperty = properties.get_Item(ref qualityIdProperty); // ReSharper disable once UseIndexedProperty qualityProperty.set_Value(ref qualityPropValue); imageFile = process.Apply(imageFile); Bitmap bitmap; // ReSharper disable once UseIndexedProperty using (var stream = new MemoryStream((byte[])imageFile.FileData.get_BinaryData())) { bitmap = new Bitmap(Image.FromStream(stream)); } return(bitmap); }
private void BgWaitStockArea_DoWork(object sender, DoWorkEventArgs e) { try { switch (e.Argument.ToString()) { case "GetInitRFIDData": using (var Client = new SRQZData.QZDataServiceClient()) { DataTable MYFunColor = Client.GetQZFunColor(context.SessionID); //获取勤哲基础颜色设置 RFIDData = Client.GetRFIDData(context.SessionID); TestRfidData = RFIDData.DefaultView; TestRfidDistinct = TestRfidData.ToTable(true, "颜色代码", "配方名称"); for (int i = 0; i < MYFunColor.Rows.Count; i++) { imageList2.Images.Add(ImageProcess.GetFillrectangleBitmap(28, 28, System.Drawing.ColorTranslator.FromHtml(MYFunColor.Rows[i]["颜色代码"].ToString()), "", Color.Black)); } } e.Result = "GetInitRFIDData"; break; } } catch (Exception ex) { Utils.Logger.Error(ex.ToString()); } }
private void Equal_MouseClick(object sender, MouseEventArgs e) { ImageProcess temp = new ImageProcess(); if (e.Button == MouseButtons.Left) { // begin to normalize data outputText.Text = ""; temp.ImageSet((Bitmap)writeArea.Image.Clone()); temp.ImageCut(); //process the DispText try { for (int i = 0; i < temp.DispText.Count; ++i) { outputText.Text += temp.DispText.ElementAt(i); } outputText.Text += "=" + new DataTable().Compute(outputText.Text, ""); } catch { outputText.Text = "Try Again!"; } } }
private void MenuOpen_OnClick(object sender, RoutedEventArgs e) { var openFileDialog = new OpenFileDialog(); { openFileDialog.Filter = "PNG图片|*.png|JPG图片|*.jpg|所有文件|*.*"; } if (openFileDialog.ShowDialog() == true) { mMat = CvInvoke.Imread(openFileDialog.FileName); SourcePic.ImageSource = BitmapHelper.BitmapToBitmapSource(mMat.ToBitmap()); imageProcess = new ImageProcess(mMat, imageMode); if (imageMode) { ImageRchannel.ImageSource = BitmapHelper.BitmapToBitmapSource(imageProcess.rImage.ToBitmap()); ImageGchannel.ImageSource = BitmapHelper.BitmapToBitmapSource(imageProcess.gImage.ToBitmap()); ImageBchannel.ImageSource = BitmapHelper.BitmapToBitmapSource(imageProcess.bImage.ToBitmap()); } else { ImageGchannel.ImageSource = BitmapHelper.BitmapToBitmapSource(imageProcess.grayImage.ToBitmap()); } modeChange(); } else { MessageBox.Show("没有选择图片"); } }
private async Task BlackWhite(CommandReplyEmbed embedrep, SocketMessage msg, List <string> args) { string url = string.IsNullOrWhiteSpace(args[0]) ? Handler.GetLastPictureURL((msg.Channel as SocketChannel)) : args[0]; string path = null; if (!string.IsNullOrWhiteSpace(url)) //if getlastpicture returns nothing { path = await ImageProcess.DownloadImage(url); } if (path != null) { try { ImageProcess.Resize(path); ImageProcess.MakeBlackWhite(path); await msg.Channel.SendFileAsync(path); ImageProcess.DeleteImage(path); }catch (Exception e) { BotLog.Debug(e.ToString()); } } if (path == null) { await embedrep.Danger(msg, "Ugh", "There's no valid url to use!"); } }
static void Main(string[] args) { Bitmap b = new Bitmap(@"C:\Users\Altran\Pictures\1.bmp"); //var imagem = b.IsExist(); //var pos = b.Possition(); //var base64 = b.ToBase64(); //b.Click(); //b.Click(0, 500); //var exist = b.IsExist(); //WindowProcess.SetFocus(@"UOL"); //var Handle = WindowProcess.GetHandle("Vivo"); //WindowProcess.SetFocus(Handle); //var handle = WindowProcess.GetHandle("UOL"); //WindowProcess.SetFocus(handle); //var wb = WebProcess.Browser("TIM"); var capt = ImageProcess.reconhecerCaptcha(b); var texto = ImageProcess.OCR(b); }
private void Button_Save_Click(object sender, RoutedEventArgs e) { try { switch (ImageInfo.Image_Extension.ToUpper()) { case ".JPG": case ".JPEG": JpegBitmapEncoder jbe = new JpegBitmapEncoder(); ImageProcess.SaveUsingEncoder(BitmapSource, ImageInfo.Image_FullPath, jbe); break; case ".PNG": PngBitmapEncoder pbe = new PngBitmapEncoder(); ImageProcess.SaveUsingEncoder(BitmapSource, ImageInfo.Image_FullPath, pbe); break; case ".GIF": GifBitmapEncoder gbe = new GifBitmapEncoder(); ImageProcess.SaveUsingEncoder(BitmapSource, ImageInfo.Image_FullPath, gbe); break; } MessageBox.Show("儲存成功", "提示", MessageBoxButton.OK); } catch (Exception ex) { Error_Log.ErrorMessageOutput(ex.ToString()); MessageBox.Show("寫入失敗", "提示", MessageBoxButton.OK, MessageBoxImage.Error); } }
public static void Test(string imgName, bool isGpu = true) { i++; //Bitmap ratedBmp; Bitmap orgBmp; orgBmp = Globles.NewReleasedBitmap(path + imgName + ".bmp"); if (orgBmp == null) { Console.WriteLine("NULL"); return; } //ratedBmp = Globles.NewBitmap(orgBmp.Width, orgBmp.Height); try { //ImageProcess.Ratezation(orgBmp, ratedBmp, isGpu); //ratedBmp.Save(path + isGpu.ToString()+ "_Rate.bmp"); CppColorRange [] crA = new CppColorRange[1]; CppColorRange cr = Init(); crA[0] = cr; //ImageProcess.Binaryzation(ratedBmp, orgBmp, cr, isGpu); ImageProcess.BinaryzationsShow__CPU(orgBmp, cr, false); orgBmp.Save(path + i + isGpu.ToString() + "_ShowCPU.bmp"); } catch (Exception ex) { //ratedBmp.Dispose(); //ratedBmp = null; Console.WriteLine(ex + ""); } //ratedBmp.Dispose(); //ratedBmp = null; orgBmp.Dispose(); orgBmp = null; }
private static void DisposeFacelessFrames(IList<Frame> motionFrames, ImageProcess.Target[] portraits) { var noPortraitFrameQuery = from m in motionFrames where !portraits.Any(t => t.BaseFrame.guid.Equals(m.Guid)) select m; Array.ForEach(noPortraitFrameQuery.ToArray(), mf => { motionFrames.Remove(mf); mf.Dispose(); }); }
/// <summary> /// loads an image for the gesture and puts it in top right corner /// </summary> /// <param name="p_gesture"></param> private void drawGesture(ref BitmapData p_data, ref byte[] p_buffer, ImageData.Gestures p_gesture) { string resourceName = ""; byte[] buffer; BitmapData data; int offset, sourceOffset; switch (p_gesture) { case ImageData.Gestures.INITIALIZING: resourceName = "initialize"; break; case ImageData.Gestures.MOVE: resourceName = "move"; break; case ImageData.Gestures.RIGHTCLICK: resourceName = "mouse_right_click"; break; case ImageData.Gestures.LEFTCLICK: resourceName = "mouse_left_click_128"; break; case ImageData.Gestures.DOUBLECLICK: resourceName = "double_click"; break; case ImageData.Gestures.CLICKANDHOLD: resourceName = "click_and_hold"; break; } Image im = (Bitmap)MotionGestureProcessing.Properties.Resources.ResourceManager.GetObject(resourceName); { convert2PixelFormat(ref im); data = BitmapManip.lockBitmap(out buffer, im); BitmapManip.unlockBitmap(ref buffer, ref data, im); } im.Dispose(); offset = sourceOffset = 0; for (int y = 0; y < data.Height; ++y) { sourceOffset = ImageProcess.getOffset(0, y, p_data.Width, 4); for (int x = 0; x < data.Width; ++x, sourceOffset += 4, offset += 4) { p_buffer[sourceOffset] = buffer[offset]; p_buffer[sourceOffset + 1] = buffer[offset + 1]; p_buffer[sourceOffset + 2] = buffer[offset + 2]; p_buffer[sourceOffset + 3] = buffer[offset + 3]; } } }
//刷新透明圖片 public void update_alpha_image() { if (alpha_image != null) { alpha_image.Dispose(); //釋放資源 } alpha_image = new Bitmap(this.Width, this.Height); //創建和controler一樣大小 ImageProcess.generate_alpha_bitmap(ref alpha_image); //生成透明貼圖 }
private void contrastToolStripMenuItem_Click(object sender, EventArgs e) { Bitmap tempImage = source; int contrastValue = Convert.ToInt32(Prompt.ShowDialog("Enter contrast value", "Contrast")); result = new Bitmap(source.Width, source.Height); //initalize the image ImageProcess.EqualisationColored(tempImage, ref source, ref result, contrastValue); outputPic.Image = result; }
public void AddToList(ImageData imageCreate) { commands1.Add(imageCreate); if (commands1.Contains(imageCreate)) { ImageProcess imageProcess = new ImageProcess(); imageProcess.ReadImage(imageCreate); } }
/// <summary> /// Handles the ItemDataBound event of the dlCatalog control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.Web.UI.WebControls.DataListItemEventArgs"/> instance containing the event data.</param> void dlCatalog_ItemDataBound(object sender, DataListItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { Product product = e.Item.DataItem as Product; if (product == null) { return; } HyperLink imageLink = e.Item.FindControl("hlImageLink") as HyperLink; site masterPage = this.Page.Master as site; if (imageLink != null && !string.IsNullOrEmpty(product.DefaultImagePath)) { imageLink.ImageUrl = ImageProcess.GetProductThumbnailUrl(product.DefaultImagePath); } Label retailPrice = e.Item.FindControl("lblRetailPrice") as Label; if (masterPage != null) { if (masterPage.SiteSettings.DisplayRetailPrice && product.RetailPrice != 0) { if (retailPrice != null) { retailPrice.Text = StoreUtility.GetFormattedAmount(product.RetailPrice, true); } } else { retailPrice.Visible = false; } } Label ourPrice = e.Item.FindControl("lblOurPrice") as Label; if (ourPrice != null) { ourPrice.Text = StoreUtility.GetFormattedAmount(product.DisplayPrice, true); } if (masterPage.SiteSettings.AddTaxToPrice && TaxService.GetDefaultTaxProvider().IsProductLevelTaxProvider) { Label taxApplied = e.Item.FindControl("lblTaxApplied") as Label; if (taxApplied != null) { taxApplied.Visible = true; } } AjaxControlToolkit.Rating ajaxRating = e.Item.FindControl("ajaxRating") as AjaxControlToolkit.Rating; if (ajaxRating != null && masterPage.SiteSettings.DisplayRatings) { ajaxRating.GroupingText = LocalizationUtility.GetText("lblAverageRating"); ajaxRating.CurrentRating = product.Rating; } else { ajaxRating.Visible = false; } } }
/*private static void BulletInBackpackEvent(ImageProcess sender, Mat mat) * { * if (!sender.Variable.ContainsKey("BinaryImage")) * sender.Variable.Add("BinaryImage", new Mat(mat.Size, DepthType.Cv8U, 1)); * * Mat BinaryImg = sender.Variable["BinaryImage"] as Mat; * ImageProcess.ElimateBackgroundWithSearchingSimilarColor(in mat, ref BinaryImg, new Color[] { Color.FromArgb(250, 0, 0) }, new uint[] { 0x00FF0000 }, ElimateColorApproach.ReserveSimilarColor_RemoveDifferentColor, 70); * // Tesseract OCR * Pix pixImage; * Page page; * try * { * pixImage = PixConverter.ToPix(BinaryImg.ToBitmap()); * page = tesseractEngine.Process(pixImage, PageSegMode.SingleBlock); * var bulletStr = page.GetText(); * page.Dispose(); * pixImage.Dispose(); * if (!string.IsNullOrEmpty(bulletStr)) * { * if (Int32.TryParse(bulletStr, out int num)) * { * publisher.Publish("BULLET", num.ToString()); #if DEBUG * Console.WriteLine($"Bullet in backpack: {num}\t"); #endif * } * } * } * catch (Exception ex) * { * Console.WriteLine("Error message: " + ex.Message); * } * }*/ private void BloodDetectorEvent(ImageProcess sender, Mat mat) { var startTick = Program.globalStopwatch.ElapsedTicks; if (!sender.Variable.ContainsKey("BinaryImage")) { sender.Variable.Add("BinaryImage", new Mat(mat.Size, DepthType.Cv8U, 1)); } if (!sender.Variable.ContainsKey("LowPassFilter_Blood")) { sender.Variable.Add("LowPassFilter_Blood", (double)1); } if (!sender.Variable.ContainsKey("BloodArea")) { double _BloodArea = mat.Height * mat.Width * 0.343; sender.Variable.Add("BloodArea", _BloodArea); } //mat.Save("HLB.png"); Mat BinaryImg = sender.Variable["BinaryImage"] as Mat; double LowPassFilter_Blood = (double)sender.Variable["LowPassFilter_Blood"]; double BloodArea = (double)sender.Variable["BloodArea"]; ImageProcess.ElimateBackgroundWithSearchingSimilarColor(in mat, ref BinaryImg, new Color[] { Color.FromArgb(250, 0, 0) }, new uint[] { 0x00FF0000 }, ElimateColorApproach.ReserveSimilarColor_RemoveDifferentColor, 40); double NowBlood; unsafe { byte *BinaryImageByteArray = (byte *)BinaryImg.DataPointer; int Offset = 0; int Area = 0; for (int y = 0; y < mat.Height; ++y) { for (int x = 0; x < mat.Width; ++x) { if (BinaryImageByteArray[Offset++] > 0) { Area++; } } } NowBlood = Area / BloodArea; } double EstimatedBlood = NowBlood * 0.2 + LowPassFilter_Blood * 0.8; #if DEBUG //Console.WriteLine($"Actual: {NowBlood.ToString("0.000")}\t Filted: {EstimatedBlood.ToString("0.000")}"); #endif if (bloodOutlet != null) { publisher.Publish(bloodOutlet, NowBlood.ToString("0.000")); } sender.Variable["LowPassFilter_Blood"] = EstimatedBlood; }
/// <summary> /// this method transforms the image into a filtered image /// UPDATE: this now performs almost insantly instead of the 2 seconds it took before /// </summary> /// <param name="p_imageData"></param> protected override async void doWork(Object p_imageData) { if (m_isInitialized) { Image procImage = ((ImageData)p_imageData).Image; //Setting up a buffer to be used for concurrent read/write byte[] buffer; convert2PixelFormat(ref procImage); BitmapData data = BitmapManip.lockBitmap(out buffer, procImage); ImageProcess.convert2GreyScale(ref buffer); #region Call Parallel.Invoke for each coordinate Parallel.Invoke( () => { //upper left dividedDoWorkARGB(buffer, 0, 0, data.Width / 2, data.Height / 2, data.Width); }, () => { //upper right dividedDoWorkARGB(buffer, data.Width / 2, 0, data.Width, data.Height / 2, data.Width); }, () => { //lower left dividedDoWorkARGB(buffer, 0, data.Height / 2, data.Width / 2, data.Height, data.Width); }, () => { //lower right dividedDoWorkARGB(buffer, data.Width / 2, data.Height / 2, data.Width, data.Height, data.Width); }); #endregion ((ImageData)p_imageData).DataPoints = ImageProcess.getDataPoints(ref data, ref buffer); //Provide finer area filtering and signal enhancing filterNoise(((ImageData)p_imageData).DataPoints, ref data, ref buffer); strengthenSignal(ref data, ref buffer); ((ImageData)p_imageData).DataPoints = findHand(ref data, ref buffer); ImageProcess.updateBuffer(((ImageData)p_imageData).DataPoints, ref data, ref buffer); BitmapManip.unlockBitmap(ref buffer, ref data, procImage); ((ImageData)p_imageData).Image = procImage; Processing.getInstance().ToPreProcessing = (ImageData)p_imageData; //If someone is listener raise an event if (ProcessReady != null) { ProcessReady(); } } }
private void SaveImageToJPEGFile(ImageFile image, string fileName) { ImageProcess imgProcess = new ImageProcess(); object convertFilter = "Convert"; string convertFilterID = imgProcess.FilterInfos.get_Item(ref convertFilter).FilterID; imgProcess.Filters.Add(convertFilterID, 0); SetWIAProperty(imgProcess.Filters[imgProcess.Filters.Count].Properties, "FormatID", WIA.FormatID.wiaFormatJPEG); image = imgProcess.Apply(image); image.SaveFile(fileName); }
private static void SaveImageToTiff(ImageFile image, string fileName) { ImageProcess imgProcess = new ImageProcess(); object convertFilter = "Convert"; string convertFilterID = imgProcess.FilterInfos.get_Item(ref convertFilter).FilterID; imgProcess.Filters.Add(convertFilterID, 0); SetWIAProperty(imgProcess.Filters[imgProcess.Filters.Count].Properties, "FormatID", WIA.FormatID.wiaFormatTIFF); image = imgProcess.Apply(image); image.SaveFile(fileName); }
public static void Do() { var db = DBSet.GetCon(DBSet.SqliteDBName.Bilibili); foreach (var imgTag in db.Select <ImageTag>(o => o.Status == "downfile_finish")) { ImageProcess.OpenCVAnalysis(imgTag); db.Update(imgTag); GC.Collect(); } }
/// <summary> /// Fetches the image list. /// </summary> /// <param name="path">The path.</param> private void FetchImageList(string path) { string mappedPath = HttpContext.Current.Server.MapPath(path); string[] images = Directory.GetFiles(mappedPath); bool mediumTrust = false; FileInfo fileInfo; try { fileInfo = new FileInfo(path); } catch (System.Security.SecurityException) { mediumTrust = true; } foreach (string img in images) { if (IsValidFileType(Path.GetExtension(img))) { Image image = new Image(); image.ImageUrl = ImageProcess.GetProductThumbnailUrl(path + Path.GetFileName(img)); image.Attributes.Add("ondblclick", "javascript:window.top.document.getElementById(\'" + controlId + "\').value=\"" + path + Path.GetFileName(img) + "\";window.top.hidePopWin(true);"); if (!mediumTrust) { fileInfo = new FileInfo(img); image.Attributes.Add("created", fileInfo.LastWriteTimeUtc.ToString()); } using (Img.Image drawnImage = Img.Image.FromFile(img)) { //do a little simple scaling //landscape if (drawnImage.Width > drawnImage.Height) { if (drawnImage.Width > 90) { image.Width = 90; image.Height = drawnImage.Height * 90 / drawnImage.Width; } } else //portrait { if (drawnImage.Height > 90) { image.Height = 90; image.Width = drawnImage.Width * 90 / drawnImage.Height; } } } imageList.Add(image); } } if (!mediumTrust) { imageList.Sort(delegate(Image a, Image b) { return(Convert.ToDateTime(b.Attributes["created"]).CompareTo(Convert.ToDateTime(a.Attributes["created"]))); }); } }
void Start() { instance = this; //Fetch a pointer to Unity's spatial coordinate system if you need pixel mapping _spatialCoordinateSystemPtr = UnityEngine.XR.WSA.WorldManager.GetNativeISpatialCoordinateSystemPtr(); //Call this in Start() to ensure that the CameraStreamHelper is already "Awake". CameraStreamHelper.Instance.GetVideoCaptureAsync(OnVideoCaptureCreated); _imageProcess = GameObject.FindObjectOfType <ImageProcess>(); }
private void SpeedDetectionEvent(ImageProcess sender, Mat mat) { #if DEBUG localDate = DateTime.Now; #endif var startTick = Program.globalStopwatch.ElapsedTicks; /* declare variables for Tesseract */ Pix pixImage; Page page; try { Bitmap BitmapFrame = mat.ToBitmap(); /* image processing */ speedImageProcess.ToBlackWhite(BitmapFrame); // grayscale(black and white) // BitmapFrame = speedImageProcess.NegativePicture(BitmapFrame); //turn into negative image speedImageProcess.ResizeImage(BitmapFrame, 120, 76); // enlarge image(x2) pixImage = PixConverter.ToPix(BitmapFrame); // PixConverter is unable to work at Tesseract 3.3.0 page = tesseractEngine.Process(pixImage, PageSegMode.SingleBlock); string speedStr = page.GetText(); // Recognized result page.Dispose(); pixImage.Dispose(); ///* Parse str to int */ bool isParsable = Int32.TryParse(speedStr, out speed); if (!isParsable || speed < 0 || speed > 300 || Math.Abs(preSpeed - speed) > 6) // 6 = 200m/s^2 { Console.WriteLine($"Error: {speed}"); // Console.WriteLine("Speed could not be parsed."); speed = preSpeed; // Can't detect speed, use the previous speed value } else { preSpeed = speed; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } if (speedOutlet != null) { publisher.Publish(speedOutlet, $"{speed}"); } #if DEBUG var time = localDate.Minute * 60 * 1000 + localDate.Second * 1000 + localDate.Millisecond; Console.WriteLine(" -Smoothed speed: " + speed + " kmh\n"); streamWriter.WriteLine(time + "," + speed); #endif }
private void BloodDetectorEvent(ImageProcess sender, Mat mat) { var startTick = Program.globalStopwatch.ElapsedTicks; double BloodValue; bool IsRedImpluse = false; unsafe { byte *OriginalImageByteArray = (byte *)mat.DataPointer; int Offset = 0; int Area = 0; //Only read the first row for (int x = 0; x < mat.Width; ++x) { //White if (OriginalImageByteArray[Offset + 2] > 180 && OriginalImageByteArray[Offset] > 180) { Area++; } //Red else if (OriginalImageByteArray[Offset + 2] > 120) { //Is Leftmost? if (x != 4) { Area++; } else if (x == 4)//Left shouldn't be red. It must be impluse { IsRedImpluse = true; } } Offset += 4; } BloodValue = Area / (double)(mat.Width); //Console.WriteLine("Blood Feature Latency: {0}", (DateTime.Now.Ticks - temp) / (double)TimeSpan.TicksPerMillisecond); } if (!IsRedImpluse) { if (bloodOutlet != null) { publisher.Publish(bloodOutlet, BloodValue.ToString()); } #if DEBUG Console.WriteLine($"Actual: {BloodValue.ToString("0.000")}"); #endif } }
public Test(int width, int height, string alphabet, int length, int tests_length) { this.alphabet = alphabet; this.tests_length = tests_length; this.length = length; tests = new string[tests_length]; img_process = new ImageProcess(width, height); System.Random rnd = new System.Random((int)System.DateTime.Now.Ticks); System.Console.WriteLine("Initialize network..."); letters_network = new NeuroNet(width * height, new int[] { 0, 2000, alphabet.Length * length }, new int[] { 0, 0 }, 1); read_filenames(); }
/// <summary> /// /// </summary> /// <param name="imagem"></param> private static string SalvarPNG(ImageFile imagem) { string fileName = CaminhoUnico(); ImageProcess imgProcess = new ImageProcess(); object convertFilter = "Convert"; string convertFilterID = imgProcess.FilterInfos.get_Item(ref convertFilter).FilterID; imgProcess.Filters.Add(convertFilterID, 0); GravaPropriedadeWIA(imgProcess.Filters[imgProcess.Filters.Count].Properties, "FormatID", WIA.FormatID.wiaFormatPNG); imagem = imgProcess.Apply(imagem); imagem.SaveFile(fileName); return(fileName); }
/// <summary> /// Uses inner to outer search to find a strong feature then /// scans from outside to in of a more reduced area to find a more accurate center /// </summary> /// <param name="p_imageData">Image data</param> /// <param name="p_data">bitmap data</param> /// <param name="p_buffer">used for testing</param> private List <Point> findHand(ref BitmapData p_data, ref byte[] p_buffer) { Dictionary <int, List <Point> > blobs = ImageProcess.findBlobs(ref p_data, ref p_buffer); if (blobs.Count > 0) { return(blobs.Aggregate((l, r) => l.Value.Count > r.Value.Count ? l : r).Value); } else { return(new List <Point>()); } }
public async Task <ActionResult <ImageObject> > Get(string ImageURL) { try { Color imageColor = Color.Transparent; using (var client = _httpClientFactory.CreateClient()) { using (HttpResponseMessage response = await client.GetAsync(ImageURL, HttpCompletionOption.ResponseHeadersRead)) { if (response.IsSuccessStatusCode) { using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync()) { imageColor = ImageProcess.ColorDetector(streamToReadFrom); //If I want to create a copy in file system. //string destinationPath = Path.Combine(_hostEnvironment.ContentRootPath, @"downloads\test1.png"); //using (Stream streamToWriteTo = System.IO.File.Open(fileToWriteTo, FileMode.Create)) //{ // await streamToReadFrom.CopyToAsync(streamToWriteTo); //} } } else { return(NotFound("Check your image URL")); } } } //ImageProcess.ColorDetector(destinationPath); ColorModel ProDigiColor = ImageProcess.GetColor(imageColor); var Output = new ImageObject() { Key = ProDigiColor.Name, Color = ProDigiColor, }; return(Ok(Output)); } catch (Exception ex) { //I prefer to use Azure ApplicationInsight. I can follow requests, failures and performance as well set an alert. _logger.LogError(ex.Message, ImageURL); return(BadRequest(ex)); } }
public string UploadPhoto() { string result; try { if (FupPhoto.HasFile) { ImageProcess img = new ImageProcess(); Stream imgStream = FupPhoto.FileContent; //validates if file is a valid JPG/PNG image bool isValidType = img.ValidateImageFileType(imgStream); //validates if file meets valid size; bool isValidSize = img.ValidateImageFileSize(imgStream, 1048576); if (isValidType == false) { return "invalid"; } if (isValidSize == false) { return "large"; } string FileExtension = Path.GetExtension(FupPhoto.FileName).ToLower(); string NewFileName = NewFileName = "Employee_" + username + "_" + StringCustomizers.dateStampNoID + FileExtension; FupPhoto.SaveAs(Server.MapPath(@"~/uploads/" + NewFileName)); result = NewFileName; } else { result = photofile; } } catch (Exception ex) { result = "error: " + ex.Message; } finally { FupPhoto.Dispose(); } return result; }
private static List<Portrait> ExpandPortraitsList(IList<Frame> motionFrames, ImageProcess.Target[] portraits) { var portraitFoundFrameQuery = from m in motionFrames join p in portraits on m.Guid equals p.BaseFrame.guid select new { Frame = m, Portraits = p, }; var expanedPortraits = from frame in portraitFoundFrameQuery from p in frame.Portraits.Portraits select new Portrait(p.Face) { FaceBounds = FrameToPortrait(p.FacesRect, p.FacesRectForCompare), FrameId = frame.Frame.Guid, CapturedAt = frame.Frame.CapturedAt, CapturedFrom = frame.Frame.CapturedFrom, }; return expanedPortraits.ToList(); }
static void Main(string[] args) { try { //Для дальнейшей обработки и кадрирования инициализируем ImageProcess imgprocess = new ImageProcess(width, height, win_width, win_height); //Случайные числа, для многопоточного обучения System.Random rnd = new System.Random((int)System.DateTime.Now.Ticks); //Инициализируем нейросеть //Сеть распознающая переломы - 4 слоя neuronet_fractures = new NeuroNet(width * height, new int[] { 0, 300,36 }, 1); fast_test_fractures(); //Инициализируем потоки обучения for (int i = 0; i < 3; i++) { //Инициализируем поток обучения сети распознающей переломы new Thread(() => teach_fracture_network(3000)).Start(); //Случайная задержка System.Threading.Thread.Sleep(rnd.Next(100, 5000)); } //Загружаем основной поток обучением переломов, дабы не простаивал teach_fracture_network(3000,1); //Случайная задержка System.Threading.Thread.Sleep(rnd.Next(100, 200)); //Пауза 500 мс, что бы все потоки успели завержиться System.Threading.Thread.Sleep(500); //Сохраняем веса для сетей neuronet_fractures.write_weights(); //Запускаем тестирование test_fractures(); //Если файл не найден System.Threading.Thread.Sleep(10000000); } catch (System.IO.FileNotFoundException e) { Console.WriteLine("File does not exist", e.Source); } }
protected void Page_Load(object sender, EventArgs e) { var ten = Request["Ten"]; var moTa = Request["MoTa"]; var id = Request["Id"]; var cUrl = Request["cUrl"]; var gioiThieu = Request["GioiThieu"]; var anh = Request["Anh"]; var duyet = Request["Duyet"]; var active = Request["Active"]; var logged = Security.IsAuthenticated(); var idNull = string.IsNullOrEmpty(id) || id == "0"; var adminKey = Request["AdminKey"]; var dic = Server.MapPath("~/lib/up/nhom/"); var joined = Request["Joined"]; var approved = Request["approved"]; var loai = Request["loai"]; switch (subAct) { case "save": #region save Nhom if (logged && !string.IsNullOrEmpty(ten)) { var item = idNull ? new Nhom() : NhomDal.SelectById(Convert.ToInt32(id)); item.Ten = ten; item.MoTa = moTa; item.GioiThieu = gioiThieu; item.Anh = anh; item.NgayCapNhat = DateTime.Now; if (!string.IsNullOrEmpty(duyet)) { duyet = !string.IsNullOrEmpty(duyet) ? "true" : "false"; item.Duyet = Convert.ToBoolean(duyet); item.NguoiDuyet = Security.Username; item.NgayDuyet = DateTime.Now; } if (!string.IsNullOrEmpty(active)) { active = !string.IsNullOrEmpty(active) ? "true" : "false"; item.Active = Convert.ToBoolean(active); } if (idNull) { item.NguoiTao = Security.Username; item.NgayTao = DateTime.Now; item.RowId = Guid.NewGuid(); item = NhomDal.Insert(item); NhomThanhVienDal.Insert(new NhomThanhVien() { NHOM_ID = item.Id , Accepted = true ,AcceptedDate = DateTime.Now , Admin = true , Approved = true , ApprovedDate = DateTime.Now , ID = Guid.NewGuid() , NgayTao = DateTime.Now , NguoiTao = Security.Username , Username = Security.Username , IsMod = true , ModLoai = 5 }); ObjMemberDal.Insert(new ObjMember() { PRowId = item.RowId , Username = Security.Username , Owner = true , NgayTao = DateTime.Now , RowId = Guid.NewGuid() }); var obj = ObjDal.Insert(new Obj() { Id = Guid.NewGuid() , Kieu = typeof(Nhom).FullName , NgayTao = DateTime.Now , RowId = item.RowId , Ten = item.Ten , Url = string.Format("{0}", item.Url) , Username = Security.Username }); } else { item.NguoiCapNhat = Security.Username; item = NhomDal.Update(item); } rendertext(item.Url); } rendertext("0"); break; #endregion case "remove": #region remove Nhom if (!string.IsNullOrEmpty(id) && logged) { var item = NhomDal.SelectById(Convert.ToInt32(id)); if (item.NguoiTao == Security.Username || !string.IsNullOrEmpty(adminKey)) { ObjDal.DeleteByRowId(item.RowId); ObjMemberDal.DeleteByPRowId(item.RowId.ToString()); ThichDal.DeleteByPId(item.RowId); NhomDal.DeleteById(item.Id); } } break; #endregion case "join": #region Tham gia nhom if (!string.IsNullOrEmpty(id) && logged) { var item = NhomDal.SelectById(DAL.con(), Convert.ToInt32(id), Security.Username); var isJoined = joined == "1"; var itemTv = NhomThanhVienDal.SelectByNhomIdUsername(id, Security.Username); if (isJoined && itemTv.ID != Guid.Empty && !itemTv.Admin) // remove { NhomThanhVienDal.DeleteById(itemTv.ID); } else // add { NhomThanhVienDal.Insert(new NhomThanhVien() { Accepted = true , AcceptedDate = DateTime.Now , Admin = false , Approved = false , ID = Guid.NewGuid() , NgayTao = DateTime.Now , NguoiTao = Security.Username , NHOM_ID = item.Id , Username = Security.Username , IsMod = false , ModLoai = 0 }); } } break; #endregion case "duyetThanhVien": #region Duyệt thành viên tham gia nhóm if (!string.IsNullOrEmpty(id) && logged) { var nhomTv = NhomThanhVienDal.SelectById(new Guid(id)); var mem = Security.Username; var memTv = NhomThanhVienDal.SelectByNhomIdUsername(nhomTv.NHOM_ID.ToString(), mem); var nhom = NhomDal.SelectById(nhomTv.NHOM_ID); var Approved = approved == "1"; if(memTv.ModLoai==5 ) { if(Approved) { nhomTv.Approved = true; nhomTv.ApprovedDate = DateTime.Now; NhomThanhVienDal.Update(nhomTv); ObjMemberDal.Insert(new ObjMember() { PRowId = nhom.RowId , Username = nhomTv.Username , Owner = false , NgayTao = DateTime.Now , RowId = Guid.NewGuid() }); } else { NhomThanhVienDal.DeleteById(nhomTv.ID); ObjMemberDal.DeleteByPRowIdUsername(nhom.RowId.ToString(), nhomTv.Username); } rendertext("1"); } rendertext("0"); } break; #endregion case "phanQuyenThanhVien": #region Phân quyền thành viên if (!string.IsNullOrEmpty(id) && logged) { var nhomTv = NhomThanhVienDal.SelectById(new Guid(id)); var mem = Security.Username; var memTv = NhomThanhVienDal.SelectByNhomIdUsername(nhomTv.NHOM_ID.ToString(), mem); if (memTv.ModLoai == 5) { nhomTv.ModLoai = Convert.ToInt32(loai); nhomTv.IsMod = nhomTv.ModLoai != 0; if(!nhomTv.Approved) { nhomTv.Approved = true; nhomTv.ApprovedDate = DateTime.Now; } NhomThanhVienDal.Update(nhomTv); rendertext("1"); } rendertext("0"); } break; #endregion case "changeAvatar": #region change avatar if (logged) { if (Request.Files.Count > 0) { var img = new ImageProcess(Request.Files[0].InputStream, Guid.NewGuid().ToString()); if (img.Width > img.Heigth) { img.ResizeHeight(180); } else { img.Resize(180); } img.Crop(180, 180); var anhNew = string.Format("{0}{1}", Guid.NewGuid().ToString(), img.Ext); img.Save(dic + anhNew); rendertext(anhNew); } } rendertext("0"); break; #endregion } }
protected void Page_Load(object sender, EventArgs e) { var ten = Request["Ten"]; var moTa = Request["MoTa"]; var keywords = Request["Keywords"]; var id = Request["Id"]; var xurl = Request["Url"]; var refId = Request["refId"]; var ngayBatDau = Request["NgayBatDau"]; var ngayKetThuc = Request["NgayKetThuc"]; var anh = Request["Anh"]; var clicked = Request["Clicked"]; var views = Request["Views"]; var logged = Security.IsAuthenticated(); var idNull = string.IsNullOrEmpty(id) || id == "0"; var adminKey = Request["AdminKey"]; var dic = Server.MapPath("~/lib/up/promoted/"); var joined = Request["Joined"]; var approved = Request["approved"]; var loai = Request["Loai"]; var pRowId = Request["PRowId"]; switch (subAct) { case "save": #region save Nhom if (logged && !string.IsNullOrEmpty(ten)) { var item = idNull ? new Promoted() : PromotedDal.SelectById(Convert.ToInt32(id)); item.Ten = ten; item.MoTa = moTa; item.Keywords = keywords; item.Anh = anh; item.Url = xurl; item.refId = refId; item.Clicked = Convert.ToInt32(clicked); item.Views = Convert.ToInt32(views); if (!string.IsNullOrEmpty(pRowId)) { item.PRowId = new Guid(pRowId); } if(!string.IsNullOrEmpty(ngayBatDau)) { item.NgayBatDau = Convert.ToDateTime(ngayBatDau, new CultureInfo("vi-Vn")); } if (!string.IsNullOrEmpty(ngayKetThuc)) { item.NgayKetThuc = Convert.ToDateTime(ngayKetThuc, new CultureInfo("vi-Vn")); } if(!string.IsNullOrEmpty(loai)) { item.Loai = Convert.ToInt32(loai); } if (!string.IsNullOrEmpty(approved)) { approved = !string.IsNullOrEmpty(approved) ? "true" : "false"; item.Approved = Convert.ToBoolean(approved); item.ApprovedBy = Security.Username; item.ApprovedDate = DateTime.Now; } else { item.Approved = false; item.ApprovedDate = DateTime.Now; } if (idNull) { item.NguoiTao = Security.Username; item.NgayTao = DateTime.Now; item.RowId = Guid.NewGuid(); item = PromotedDal.Insert(item); } else { item = PromotedDal.Update(item); } rendertext(item.Url); } rendertext("0"); break; #endregion case "remove": #region remove Nhom if (!string.IsNullOrEmpty(id) && logged) { PromotedDal.DeleteById(Convert.ToInt32(id)); } break; #endregion case "changeAvatar": #region change avatar if (logged) { if (Request.Files.Count > 0) { var img = new ImageProcess(Request.Files[0].InputStream, Guid.NewGuid().ToString()); if (img.Width > 300) { img.Resize(300); } var anhNew = string.Format("{0}{1}", Guid.NewGuid().ToString(), img.Ext); img.Save(dic + anhNew); rendertext(anhNew); } } rendertext("0"); break; #endregion } RemoveCache(); }
protected void Page_Load(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); string imgSaveLoc = Server.MapPath("~/lib/up/i/"); string imgSaveTintuc = Server.MapPath("~/lib/up/tintuc/"); string imgTemp = Server.MapPath("~/lib/up/temp/"); string docTemp = Server.MapPath("~/lib/up/d/"); bool loggedIn = Security.IsAuthenticated(); insertLog("0", Security.Username, Request.UserHostAddress, Request.Url.PathAndQuery); switch (act) { case "loadPlug": if (rqPlug != null) { sb.Append(PlugHelper.RenderHtml(rqPlug)); } rendertext(sb); break; case "upload": #region upload ảnh if (Security.IsAuthenticated()) { if (Request.Files[0] != null) { string imgten = Guid.NewGuid().ToString(); if (!string.IsNullOrEmpty(Request["oldFile"])) { try { imgten = Path.GetFileNameWithoutExtension(Request["oldFile"]); if (File.Exists(imgSaveLoc + Request["oldFile"])) { File.Delete(imgSaveLoc + Request["oldFile"]); } } finally { } } ImageProcess img = new ImageProcess(Request.Files[0].InputStream, Guid.NewGuid().ToString()); img.Crop(730, 600); img.Save(imgSaveLoc + imgten + "730x600" + img.Ext); img.Crop(420, 280); img.Save(imgSaveLoc + imgten + "420x280" + img.Ext); img.Crop(130, 100); img.Save(imgSaveLoc + imgten + img.Ext); rendertext(imgten + img.Ext); } } break; #endregion case "uploadTintuc": #region upload ảnh if (Security.IsAuthenticated()) { if (Request.Files[0] != null) { string imgten = Guid.NewGuid().ToString(); if (!string.IsNullOrEmpty(Request["oldFile"])) { try { imgten = Path.GetFileNameWithoutExtension(Request["oldFile"]); if (File.Exists(imgSaveLoc + Request["oldFile"])) { File.Delete(imgSaveLoc + Request["oldFile"]); } } finally { } } ImageProcess img = new ImageProcess(Request.Files[0].InputStream, Guid.NewGuid().ToString()); img.Crop(730, 600); img.Save(imgSaveTintuc + imgten + "730x600" + img.Ext); img.Crop(420, 280); img.Save(imgSaveTintuc + imgten + "420x280" + img.Ext); img.Crop(130, 100); img.Save(imgSaveTintuc + imgten + img.Ext); rendertext(imgten + img.Ext); } } break; #endregion case "uploadFull": #region upload ảnh if (Security.IsAuthenticated()) { if (Request.Files[0] != null) { string imgten = Guid.NewGuid().ToString(); if (!string.IsNullOrEmpty(Request["oldFile"])) { try { imgten = Path.GetFileNameWithoutExtension(Request["oldFile"]); if (File.Exists(imgSaveLoc + Request["oldFile"])) { File.Delete(imgSaveLoc + Request["oldFile"]); } } finally { } } ImageProcess img = new ImageProcess(Request.Files[0].InputStream, Guid.NewGuid().ToString()); img.Save(imgSaveLoc + imgten + img.Ext); rendertext(imgten + img.Ext); } } break; #endregion case "uploadfileDkLuong": #region upload tài liệu if (!loggedIn) rendertext("403"); if (Request.Files[0] != null) { string foldername = Guid.NewGuid().ToString().Replace("-", ""); string filename = Path.GetFileNameWithoutExtension(Request.Files[0].FileName); string fileType = Path.GetExtension(Request.Files[0].FileName); Directory.CreateDirectory(docTemp + foldername); Request.Files[0].SaveAs(docTemp + foldername + "/" + filename + fileType); Files item = new Files(); item.Download = 0; item.MimeType = fileType; item.NgayTao = DateTime.Now; item.NguoiTao = Security.Username; item.Path = filename; item.PID = Guid.NewGuid(); item.RowId = Guid.NewGuid(); item.Size = Request.Files[0].ContentLength; item.Ten = filename; item.ThuMuc = foldername; item.VB_ID = 0; item = FilesDal.Insert(item); rendertext(item.ID.ToString()); } break; #endregion case "download": string _F_ID = Request["ID"]; if (!string.IsNullOrEmpty(_F_ID)) { Files item = FilesDal.SelectById(Convert.ToInt32(_F_ID)); Response.Buffer = true; Response.Clear(); Response.AddHeader("content-disposition", "attachment; filename=\"" + item.Ten + item.MimeType + "\""); Response.ContentType = "octet/stream"; //Response.ContentType = "application/ms-word"; Response.WriteFile(Server.MapPath("~/lib/up/d/") + item.ThuMuc + "/" + item.Path + item.MimeType); } break; case "loadPlugDirect": if (!string.IsNullOrEmpty(rqPlug)) { string _IPlugType = rqPlug; Type type = Type.GetType(_IPlugType); IPlug _IPlug = (IPlug)(Activator.CreateInstance(type)); _IPlug.ImportPlugin(); Page pageHolder = new Page(); UserControl uc = (UserControl)(_IPlug); this.Controls.Add(uc); } break; case "uploadvideo": break; default: string d = "12/9/2010"; //DateTime da = Convert.ToDateTime(d, new System.Globalization.CultureInfo("vi-Vn")); //Response.Write(da.Month.ToString()); Response.Write(maHoa.EncryptString("111", "phatcd")); break; } }
void SaveAvatar(int id, string fbid, string dic) { var url = string.Format("http://graph.facebook.com/{0}/picture?type=large", fbid); var rq = (HttpWebRequest)(WebRequest.Create(url)); rq.UserAgent = uAgent; rq.Timeout = 20000; var rp = (HttpWebResponse)(rq.GetResponse()); var newUri = rp.ResponseUri; var img = new ImageProcess(newUri, url); img.Crop(180, 180); var ten = string.Format("{0}{1}", id, img.Ext); img.Save(dic + ten); var user = MemberDal.SelectById(id); MemberDal.UpdateAnh(user.Username, ten); }
protected void Page_Load(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); string imgSaveLoc = Server.MapPath("~/lib/up/i/"); string imgSaveTintuc = Server.MapPath("~/lib/up/tintuc/"); string imgTemp = Server.MapPath("~/lib/up/temp/"); string docTemp = Server.MapPath("~/lib/up/d/"); bool loggedIn = Security.IsAuthenticated(); insertLog("0", Security.Username, Request.UserHostAddress, Request.Url.PathAndQuery); switch (act) { case "loadPlug": if (rqPlug != null) { sb.Append(PlugHelper.RenderHtml(rqPlug)); } rendertext(sb); break; case "loadPlugContent": if (rqPlug != null) { Type type = Type.GetType(rqPlug); IPlug plug = (IPlug)Activator.CreateInstance(type); plug.ImportPlugin(); using (SqlConnection con = linh.core.dal.DAL.con()) { plug.KhoiTao(con); rendertext(plug.Html); } } rendertext(sb); break; case "upload": #region upload ảnh if (Security.IsAuthenticated()) { if (Request.Files[0] != null) { string imgten = Guid.NewGuid().ToString(); if (!string.IsNullOrEmpty(Request["oldFile"])) { try { imgten = Path.GetFileNameWithoutExtension(Request["oldFile"]); if (File.Exists(imgSaveLoc + Request["oldFile"])) { File.Delete(imgSaveLoc + Request["oldFile"]); } } finally { } } ImageProcess img = new ImageProcess(Request.Files[0].InputStream, Guid.NewGuid().ToString()); img.Crop(730, 600); img.Save(imgSaveLoc + imgten + "730x600" + img.Ext); img.Crop(420, 280); img.Save(imgSaveLoc + imgten + "420x280" + img.Ext); img.Crop(130, 100); img.Save(imgSaveLoc + imgten + img.Ext); rendertext(imgten + img.Ext); } } break; #endregion case "uploadTintuc": #region upload ảnh if (Security.IsAuthenticated()) { if (Request.Files[0] != null) { string imgten = Guid.NewGuid().ToString(); if (!string.IsNullOrEmpty(Request["oldFile"])) { try { imgten = Path.GetFileNameWithoutExtension(Request["oldFile"]); if (File.Exists(imgSaveLoc + Request["oldFile"])) { File.Delete(imgSaveLoc + Request["oldFile"]); } } finally { } } ImageProcess img = new ImageProcess(Request.Files[0].InputStream, Guid.NewGuid().ToString()); img.Crop(730, 600); img.Save(imgSaveTintuc + imgten + "730x600" + img.Ext); img.Crop(420, 280); img.Save(imgSaveTintuc + imgten + "420x280" + img.Ext); img.Crop(130, 100); img.Save(imgSaveTintuc + imgten + img.Ext); rendertext(imgten + img.Ext); } } break; #endregion case "uploadFull": #region upload ảnh if (Security.IsAuthenticated()) { if (Request.Files[0] != null) { string imgten = Guid.NewGuid().ToString(); if (!string.IsNullOrEmpty(Request["oldFile"])) { try { imgten = Path.GetFileNameWithoutExtension(Request["oldFile"]); if (File.Exists(imgSaveLoc + Request["oldFile"])) { File.Delete(imgSaveLoc + Request["oldFile"]); } } finally { } } ImageProcess img = new ImageProcess(Request.Files[0].InputStream, Guid.NewGuid().ToString()); img.Save(imgSaveLoc + imgten + img.Ext); rendertext(imgten + img.Ext); } } break; #endregion case "loadPlugDirect": if (!string.IsNullOrEmpty(rqPlug)) { string _IPlugType = rqPlug; Type type = Type.GetType(_IPlugType); IPlug _IPlug = (IPlug)(Activator.CreateInstance(type)); _IPlug.ImportPlugin(); Page pageHolder = new Page(); UserControl uc = (UserControl)(_IPlug); this.Controls.Add(uc); } break; default: string d = "12/9/2010"; //DateTime da = Convert.ToDateTime(d, new System.Globalization.CultureInfo("vi-Vn")); //Response.Write(da.Month.ToString()); Response.Write(maHoa.EncryptString("111", "phatcd")); break; } }
protected void Page_Load(object sender, EventArgs e) { var logged = Security.IsAuthenticated(); var dic = Server.MapPath("~/lib/up/users/"); var Ten = Request["Ten"]; var MoTa = Request["MoTa"]; var Mobile = Request["Mobile"]; var Tinh_ID = Request["Tinh_ID"]; var Alias = Request["Alias"]; var rowId = Request["RowId"]; switch (subAct) { case "changeAvatar": #region change avatar if(logged) { if(Request.Files.Count > 0) { var img = new ImageProcess(Request.Files[0].InputStream, Guid.NewGuid().ToString()); if(img.Width > img.Heigth) { img.ResizeHeight(180); } else { img.Resize(180); } img.Crop(180, 180); var user = MemberDal.SelectByUser(Security.Username); var anh = dic + user.Anh; if(!string.IsNullOrEmpty(anh)) { if(File.Exists(anh)) File.Delete(anh); } var anhNew = string.Format("{0}{1}", user.Id, img.Ext); img.Save(dic + anhNew); MemberDal.UpdateAnh(Security.Username,anhNew); rendertext(anhNew); } } rendertext("0"); break; #endregion case "validateAlias": #region validate object alias if (logged && !string.IsNullOrEmpty(rowId) && !string.IsNullOrEmpty(Alias)) { var RowId = new Guid(rowId); var obj = ObjDal.SelectByAlias(Alias); if(obj.Id == Guid.Empty) { rendertext("1"); } else { if (obj.RowId == RowId) { rendertext("1"); } else { rendertext("0"); } } rendertext("0"); } rendertext("0"); break; #endregion case "saveAlias": #region validate object alias if (logged && !string.IsNullOrEmpty(rowId) && !string.IsNullOrEmpty(Alias)) { var RowId = new Guid(rowId); var obj = ObjDal.SelectByAlias(Alias); if (obj.Id == Guid.Empty) { obj = ObjDal.SelectByRowId(RowId); obj.Alias = Alias; ObjDal.Update(obj); rendertext("1"); } else { if (obj.RowId == RowId) { rendertext("1"); } else { rendertext("0"); } } rendertext("0"); } rendertext("0"); break; #endregion case "GetVcard": #region change avatar vcard.Visible = true; break; #endregion case "saveInformation": #region Store information if (logged && !string.IsNullOrEmpty(Ten)) { var user = MemberDal.SelectByUser(Security.Username); if(!string.IsNullOrEmpty(Tinh_ID)) { user.Tinh = new Guid(Tinh_ID); } user.Ten = Ten; user.Mota = MoTa; user.Mobile = Mobile; user.NgayCapNhat = DateTime.Now; user = MemberDal.Update(user); Security.Login(user.Username, "true"); MemberDal.UpdateVcard(DAL.con(), user.Username); rendertext("1"); } rendertext("0"); break; #endregion } }
public ImageProcessRunner(IPParams param) { this.param = param; ip = new ImageProcess(param); }
protected void Page_Load(object sender, EventArgs e) { var x = Request["x"]; var y = Request["y"]; var x1 = Request["x1"]; var y1 = Request["y1"]; var w = Request["w"]; var h = Request["h"]; var Key = Request["key"]; var Id = Request["Id"]; var dic = Server.MapPath("~/lib/up/crop/"); var newDic = Server.MapPath("~/lib/up/car/"); var DM_PID = Request["DM_PID"]; var logged = Security.IsAuthenticated(); var js = new JavaScriptSerializer(); switch (subAct) { case "upload": #region upload image if (!string.IsNullOrEmpty(Id)) { Response.ContentType = "text/plain";//"application/json"; var r = new List<ViewDataUploadFilesResult>(); foreach (string file in Request.Files) { var hpf = Request.Files[file] as HttpPostedFile; var key = Guid.NewGuid().ToString(); var img = new ImageProcess(hpf.InputStream, key); var fileName = key + img.Ext; img.Resize(960); img.Save(dic + key + "full" + img.Ext); img.Save(dic + key + img.Ext); var anh = new Anh() { Id = Guid.NewGuid() , P_ID = new Guid(Id) , FileAnh = fileName , NgayTao = DateTime.Now }; anh = AnhDal.Insert(anh); r.Add(new ViewDataUploadFilesResult() { Id = anh.Id.ToString(), Thumbnail_url = key + img.Ext, Name = key + "full" + img.Ext, Length = hpf.ContentLength, Type = hpf.ContentType }); var uploadedFiles = new { files = r.ToArray() }; var jsonObj = js.Serialize(uploadedFiles); rendertext(jsonObj); } } rendertext("Id is missing", HttpStatusCode.BadRequest); break; #endregion case "GetImage": #region get image if (Key != null) { var fileName = dic + Lib.imgSize(Key, "full"); var src = new Bitmap(fileName); var cropRect = new Rectangle(Convert.ToInt32(x), Convert.ToInt32(y), Convert.ToInt32(w), Convert.ToInt32(h)); var cropted = Lib.CropBitmap(src, cropRect); var img = new ImageProcess(cropted, Key); File.Delete(dic + Key); if (img.Width < 960) img.Resize(960); Response.ClearContent(); Response.ContentType = img.Mime; img.Save(newDic + Key); img.Save(); Response.End(); } break; #endregion case "RemoveImage": #region remove image if (Id != null) { var item = AnhDal.SelectById(new Guid(Id)); var file = newDic + item.FileAnh; if (File.Exists(file)) { File.Delete(newDic + item.FileAnh); } AnhDal.DeleteById(item.Id); } break; #endregion case "SetAnhChinh": #region Set Anh Chinh if (Id != null) { var item = AnhDal.SelectById(new Guid(Id)); AnhDal.UpdateAnhBia(item.Id); var xe = XeDal.SelectByRowId(item.P_ID); if (xe.Id != 0) { xe.Anh = item.FileAnh; XeDal.Update(xe); } var blog = BlogDal.SelectByRowId(item.P_ID); if (blog.Id != 0) { blog.Anh = item.FileAnh; BlogDal.Update(blog); } } break; #endregion case "GetImageMobile": #region get image in mobile if (Key != null) { var fileName = dic + Lib.imgSize(Key, "full"); var img = new ImageProcess(fileName, Key); File.Delete(dic + Key); if (img.Heigth < 540) img.ResizeHeight(540); img.Crop(960, 540); Response.ClearContent(); Response.ContentType = img.Mime; img.Save(newDic + Key); if(!string.IsNullOrEmpty(w)) { img.Resize(Convert.ToInt32(w)); if(!string.IsNullOrEmpty(h)) { img.Crop(Convert.ToInt32(w), Convert.ToInt32(h)); } } img.Save(); Response.End(); } break; #endregion } }