当前位置: 首页>>代码示例>>C#>>正文


C# UIImage.AsJPEG方法代码示例

本文整理汇总了C#中UIKit.UIImage.AsJPEG方法的典型用法代码示例。如果您正苦于以下问题:C# UIImage.AsJPEG方法的具体用法?C# UIImage.AsJPEG怎么用?C# UIImage.AsJPEG使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在UIKit.UIImage的用法示例。


在下文中一共展示了UIImage.AsJPEG方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetData

 private static NSData GetData(UIImage image, ImageType type, int quality)
 {
     var floatQuality = quality/100f;
     switch(type)
     {
         case ImageType.Jpg:
             return image.AsJPEG(floatQuality);
         case ImageType.Png:
             return image.AsPNG();
         default:
             return image.AsJPEG(floatQuality);
     }
 } 
开发者ID:rsc092020,项目名称:Xamarin.ImageScaling,代码行数:13,代码来源:ImageScalingImplementation.cs

示例2: SaveImage

        public async Task<bool> SaveImage(ImageSource img, string imageName)
        {
            var render = new StreamImagesourceHandler();

            image = await render.LoadImageAsync(img);

            var path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            var nomeImagem = Path.Combine(path, imageName);

            NSData imgData = image.AsJPEG();
            NSError erro = null;

            return imgData.Save(nomeImagem, false, out erro);
        }
开发者ID:jbravobr,项目名称:Mais-XamForms,代码行数:14,代码来源:SaveAndLoadFile_IOS.cs

示例3: setImage

        public static void setImage(UIImage i, string s)
        {
            dictionary.Add(s, i);

            // Create full path for image
            string imagePath = imagePathForKey(s);

            // Turn image into JPG/PNG data.
            NSData d = i.AsJPEG(0.5f);

            // Write it to the full path
            NSError error = new NSError(new NSString("ImageSaveError"), 404);
            d.Save(imagePath, NSDataWritingOptions.Atomic, out error);
        }
开发者ID:yingfangdu,项目名称:BNR,代码行数:14,代码来源:BNRImageStore.cs

示例4: SendTo

        /// <summary>
        /// Sends the specified UIImage to the AirPlay device.
        /// </summary>
        /// <param name='service'>
        /// NSNetService (extension method target) representing the AirPlay device.
        /// </param>
        /// <param name='image'>
        /// The UIImage to be send to the device.
        /// </param>
        /// <param name='complete'>
        /// Optional method to be called when the operation is complete. True will be supplied if the action was
        /// successful, false if a problem occured.
        /// </param>
        public static unsafe void SendTo(this NSNetService service, UIImage image, Action<bool> complete)
        {
            if (service == null) {
                if (complete != null)
                    complete (false);
                return;
            }

            // In general I prefer WebClient *Async methods but it does not provide methods to
            // upload Stream and allocating a (not really required) byte[] is a huge waste
            ThreadPool.QueueUserWorkItem (delegate {
                bool ok = true;
                try {
                    string url = String.Format ("http://{0}:{1}/photo", service.HostName, service.Port);
                    var req = (HttpWebRequest) WebRequest.Create (url);
                    using (var data = image.AsJPEG ()) {
                        req.Method = "PUT";
                        req.ContentLength = (int) data.Length;
                        req.UserAgent = "AirPlay/160.4 (Photos)";
                        req.Headers.Add ("X-Apple-AssetKey", Guid.NewGuid ().ToString ());
                        req.Headers.Add ("X-Apple-Session-ID", session.ToString ());
                        var s = req.GetRequestStream ();
                        using (Stream ums = new UnmanagedMemoryStream ((byte *) data.Bytes, (int) data.Length))
                            ums.CopyTo (s);
                    }
                    req.GetResponse ().Dispose ();
                }
                catch {
                    ok = false;
                }
                finally {
                    if (complete != null) {
                        NSRunLoop.Main.InvokeOnMainThread (delegate {
                            complete (ok);
                        });
                    }
                }
            });
        }
开发者ID:spouliot,项目名称:airplay,代码行数:52,代码来源:AirPlayRocks.cs

示例5: ImageData

		public ImageData (UIImage image, string filename)
		{
			if (image == null) {
				throw new ArgumentNullException ("image");
			}
			if (string.IsNullOrEmpty (filename)) {
				throw new ArgumentException ("filename");
			}

			Image = image;
			Filename = filename;

			MimeType = (filename.ToLowerInvariant ().EndsWith (".png")) ?
				"image/png" : "image/jpeg";

			if (MimeType == "image/png") {
				Data = new NSDataStream (image.AsPNG ());
			}
			else {
				Data = new NSDataStream (image.AsJPEG ());
			}
		}
开发者ID:nissan,项目名称:Xamarin.Social,代码行数:22,代码来源:ImageData.cs

示例6: HandleImagePick

        private void HandleImagePick(UIImage image, string name)
        {
            ClearCurrentlyActive();
            if (image != null)
            {
                if (_maxPixelDimension > 0 && (image.Size.Height > _maxPixelDimension || image.Size.Width > _maxPixelDimension))
                {
                    // resize the image
                    image = image.ImageToFitSize(new CGSize(_maxPixelDimension, _maxPixelDimension));
                }

                using (NSData data = image.AsJPEG(_percentQuality / 100f))
                {
                    var byteArray = new byte[data.Length];
                    Marshal.Copy(data.Bytes, byteArray, 0, Convert.ToInt32(data.Length));

                    var imageStream = new MemoryStream(byteArray, false);
                    _pictureAvailable?.Invoke(imageStream, name);
                }
            }
            else
            {
                _assumeCancelled?.Invoke();
            }

            _picker.DismissViewController(true, () => { });
            _modalHost.NativeModalViewControllerDisappearedOnItsOwn();
        }
开发者ID:ChebMami38,项目名称:MvvmCross-Plugins,代码行数:28,代码来源:MvxImagePickerTask.cs

示例7: GetImageStream

        private static Stream GetImageStream(UIImage image, ImageFormatType formatType)
        {
            if (formatType == ImageFormatType.Jpg)
                return image.AsJPEG().AsStream();

            return image.AsPNG().AsStream();
        }
开发者ID:mrbelk,项目名称:acr-xamarin-forms,代码行数:7,代码来源:SignatureServiceController.cs

示例8: UpdateAsset

		// this function will check if the asset corresponding to the localIdentifier passed in is already in the bugTrap album.
		// If it is, it will update the existing asset and return nil in the callback, otherwise, a new (duplicate) will be created
		// and the localIdentifier of the newly created asset will be returned by the callback

		public async Task<string> UpdateAsset (UIImage updatedSnapshot, string localIdentifier)
		{
			var tcs = new TaskCompletionSource<string> ();

			var collectionLocalIdentifier = await GetAlbumLocalIdentifier();

			if (string.IsNullOrEmpty(collectionLocalIdentifier)) return null;

			// get the bugTrap album
			var bugTrapAlbum = PHAssetCollection.FetchAssetCollections(new [] { collectionLocalIdentifier }, null)?.firstObject as PHAssetCollection;
			if (bugTrapAlbum != null) {

				// if we passed in null for the localIdentifier, we just want to save the image and
				// get a new identifier (most likely being used as the sdk)
				if (string.IsNullOrEmpty(localIdentifier)) {
					return await SaveAsset(updatedSnapshot, bugTrapAlbum, tcs);
				}

				// get the asset for the localIdentifier
				var asset = PHAsset.FetchAssetsUsingLocalIdentifiers(new [] { localIdentifier }, null)?.firstObject as PHAsset;
				if (asset != null) {

					// get all the albums containing this asset
					var containingAssetResults = PHAssetCollection.FetchAssetCollections(asset, PHAssetCollectionType.Album, null);
					if (containingAssetResults != null) {
						
						// check if any of the albums is the bugTrap album.  if the asset is already in the bugTrap album, update the existing asset.
						if (containingAssetResults.Contains(bugTrapAlbum)) {

							// retrieve a PHContentEditingInput object
							asset.RequestContentEditingInput(null, async (input, info) => 

								PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => {
								
								var editAssetOutput = new PHContentEditingOutput (input);
								editAssetOutput.AdjustmentData = new PHAdjustmentData ("io.bugtrap.bugTrap", "1.0.0", NSData.FromString("io.bugtrap.bugTrap"));
								
								var editAssetJpegData = updatedSnapshot.AsJPEG(1);
								editAssetJpegData.Save(editAssetOutput.RenderedContentUrl, true);

								var editAssetRequest = PHAssetChangeRequest.ChangeRequest(asset);
								editAssetRequest.ContentEditingOutput = editAssetOutput;

							}, (success, error) => {

								if (success) {

									if (!tcs.TrySetResult(null)) {
										var ex = new Exception ("UpdateAsset Failed");
										tcs.TrySetException(ex);
										// Log.Error(ex);
									}

								} else if (error != null) {
									// Log.Error("Photos", error);
									if (!tcs.TrySetResult(null)) {
										var ex = new Exception (error.LocalizedDescription);
										tcs.TrySetException(ex);
										// Log.Error(ex);
									}
								}
							}));
									
						} else {// if the asset isn't in the bugTrap album, create a new asset and put it in the album, and leave the original unchanged

							return await SaveAsset(updatedSnapshot, bugTrapAlbum, tcs);

//							string newLocalIdentifier = null;
//
//							PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => {
//
//								// create a new asset from the UIImage updatedSnapshot
//								var createAssetRequest = PHAssetChangeRequest.FromImage(updatedSnapshot);
//
//								// create a request to make changes to the bugTrap album
//								var collectionRequest = PHAssetCollectionChangeRequest.ChangeRequest(bugTrapAlbum);
//
//								// get a reference to the new localIdentifier
//								newLocalIdentifier = createAssetRequest.PlaceholderForCreatedAsset.LocalIdentifier;
//
//								// add the newly created asset to the bugTrap album
//								collectionRequest.AddAssets(new [] { createAssetRequest.PlaceholderForCreatedAsset });
//
//							}, (success, error) => {
//
//								if (success) {
//
//									if (!tcs.TrySetResult(newLocalIdentifier)) {
//										var ex = new Exception ("UpdateAsset Failed");
//										tcs.TrySetException(ex);
//										// Log.Error(ex);
//									}
//
//								} else if (error != null) {
//									// Log.Error("Photos", error);
//									if (!tcs.TrySetResult(null)) {
//.........这里部分代码省略.........
开发者ID:colbylwilliams,项目名称:bugtrap,代码行数:101,代码来源:Photos.cs

示例9: ByteArrayFromImage

		public static byte[] ByteArrayFromImage(UIImage image, int quality = 50)
		{
			nfloat myQuality = 1.0f;

			if (quality == 0)
				myQuality = 0.0f;
			else
				myQuality = ((nfloat)quality) / ((nfloat)100);

			using (NSData imageData = image.AsJPEG(myQuality))
			{
				Byte[] myByteArray = new Byte[imageData.Length];
				System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, myByteArray, 0, Convert.ToInt32(imageData.Length));
				return myByteArray;
			}
		}
开发者ID:natevarghese,项目名称:XamarinTen,代码行数:16,代码来源:ImageUtils.cs

示例10: ToBase64

		public static string ToBase64(UIImage image){
			return image.AsJPEG().GetBase64EncodedData (NSDataBase64EncodingOptions.None).ToString ();
		}
开发者ID:natevarghese,项目名称:XamarinTen,代码行数:3,代码来源:ImageUtils.cs

示例11: SendImage

    private async void SendImage(UIImage image)
    {
      try
      {
        using (ISitecoreWebApiSession session = this.instanceSettings.GetSession())
        {
          Stream stream = image.AsJPEG().AsStream();

          var request = ItemWebApiRequestBuilder.UploadResourceRequestWithParentPath(itemPathTextField.Text)
            .ItemDataStream(stream)
            .ContentType("image/jpg")
            .ItemName(this.itemNameTextField.Text)
            .FileName("imageFile.jpg")
            .Build();

          this.ShowLoader();

          var response = await session.UploadMediaResourceAsync(request);

          if (response != null)
          {
            AlertHelper.ShowAlertWithOkOption("upload image result","The image uploaded successfuly");
          }
          else
          {
            AlertHelper.ShowAlertWithOkOption("upload image result","something wrong");
          }
        }
      }
      catch(Exception e) 
      {
        AlertHelper.ShowLocalizedAlertWithOkOption("Error", e.Message);
      }
      finally
      {
        BeginInvokeOnMainThread(delegate
        {
          this.HideLoader();
        });
      }
    }
开发者ID:amatkivskiy,项目名称:sitecore-xamarin-pcl-sdk,代码行数:41,代码来源:UploadImageViewController.cs

示例12: SaveToTmp

		static NSUrl SaveToTmp (UIImage img, string fileName)
		{
			var tmp = Path.GetTempPath ();
			string path = Path.Combine (tmp, fileName);

			NSData imageData = img.AsJPEG (0.5f);
			imageData.Save (path, true);

			var url = new NSUrl (path, false);
			return url;
		}
开发者ID:CBrauer,项目名称:monotouch-samples,代码行数:11,代码来源:Image.cs

示例13: UploadImage

		public async Task<string> UploadImage(UIImage image, string ext)
		{

			var sasurl = await client.InvokeApiAsync<string>("UsersCustom/GetUploadURL/",HttpMethod.Get,null);
			string imageurl = "";

			CloudBlobContainer container = new CloudBlobContainer(new Uri(sasurl));
			//Write operation: write a new blob to the container.
			CloudBlockBlob blob = container.GetBlockBlobReference(CurrentUser.Id + "_" + DateTime.Now.Ticks + "." + ext);
			blob.Properties.ContentType = "image/jpg";
			imageurl =blob.Uri.AbsoluteUri;
			CurrentUser.ImageUrl = imageurl;

			try
			{
				await blob.UploadFromStreamAsync(image.AsJPEG().AsStream());
			}
			catch (Exception e) {
				Console.WriteLine ("Write operation failed for SAS " + sasurl);
				Console.WriteLine ("Additional error information: " + e.Message);
				Console.WriteLine ();
			}

			await UpdateCurrentUser ();

			return imageurl;

		}
开发者ID:soleary1222,项目名称:prayerapplication,代码行数:28,代码来源:PrayerService.cs

示例14: GetImageSourceFromUIImage

 internal static ImageSource GetImageSourceFromUIImage(UIImage uiImage)
 {
     return uiImage == null ? null : ImageSource.FromStream(() => uiImage.AsJPEG(0.75f).AsStream());
 }
开发者ID:jimbobbennett,项目名称:JimLib.Xamarin,代码行数:4,代码来源:ImageHelper.cs

示例15: UploadImage

        private async void UploadImage(UIImage img)
        {
            var hud = new CodeHub.iOS.Utilities.Hud(null);
            hud.Show("Uploading...");

            try
            {
                var returnData = await Task.Run<byte[]>(() => 
                {
                    using (var w = new WebClient())
                    {
                        var data = img.AsJPEG();
                        byte[] dataBytes = new byte[data.Length];
                        System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length));

                        w.Headers.Set("Authorization", "Client-ID aa5d7d0bc1dffa6");

                        var values = new NameValueCollection
                        {
                            { "image", Convert.ToBase64String(dataBytes) }
                        };

                        return w.UploadValues("https://api.imgur.com/3/image", values);
                    }
                });


                var json = Mvx.Resolve<IJsonSerializationService>();
                var imgurModel = json.Deserialize<ImgurModel>(System.Text.Encoding.UTF8.GetString(returnData));
                TextView.InsertText("![](" + imgurModel.Data.Link + ")");
            }
            catch (Exception e)
            {
                AlertDialogService.ShowAlert("Error", "Unable to upload image: " + e.Message);
            }
            finally
            {
                hud.Hide();
            }
        }
开发者ID:GitWatcher,项目名称:CodeHub,代码行数:40,代码来源:MarkdownComposerViewController.cs


注:本文中的UIKit.UIImage.AsJPEG方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。