本文整理汇总了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);
}
}
示例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);
}
示例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);
}
示例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);
});
}
}
});
}
示例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 ());
}
}
示例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();
}
示例7: GetImageStream
private static Stream GetImageStream(UIImage image, ImageFormatType formatType)
{
if (formatType == ImageFormatType.Jpg)
return image.AsJPEG().AsStream();
return image.AsPNG().AsStream();
}
示例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)) {
//.........这里部分代码省略.........
示例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;
}
}
示例10: ToBase64
public static string ToBase64(UIImage image){
return image.AsJPEG().GetBase64EncodedData (NSDataBase64EncodingOptions.None).ToString ();
}
示例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();
});
}
}
示例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;
}
示例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;
}
示例14: GetImageSourceFromUIImage
internal static ImageSource GetImageSourceFromUIImage(UIImage uiImage)
{
return uiImage == null ? null : ImageSource.FromStream(() => uiImage.AsJPEG(0.75f).AsStream());
}
示例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();
}
}