ios - 如何缩小iphone 7中相机拍摄的照片的大小

标签 ios web-services xamarin.ios

我正在研究 xamarin ios。我必须在 iphone 应用程序中实现相机功能。我已经实现了代码。但问题是,当我尝试使用 web 服务上传图片时,由于图片的大小而无法上传。

所以我尝试缩放图片的大小,但在那种情况下图像看起来被拉伸(stretch)了。我希望该图片应该以相同的尺寸上传,可能质量最差,但高度和宽度应该是原始的。

这是我实现的代码:

Camera.TakePicture(this, (obj) =>
            {
                var photo = obj.ValueForKey(new NSString("UIImagePickerControllerOriginalImage")) as UIImage;
                var image = photo.Scale(new CGSize(1280, 720));
                Byte[] myByteArray;
                using (NSData imageData = image.AsJPEG(0.0f))
                {

                    myByteArray = new Byte[imageData.Length];
                    System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, myByteArray, 0, Convert.ToInt32(imageData.Length));
                }

            }); 

最佳答案

不执行缩放操作

var image = photo.Scale(new CGSize(1280, 720));

如果您不想更改尺寸。如果您确实想调整大小并保持纵横比,这段代码应该可以做到

// Resize the image to be contained within a maximum width and height, keeping aspect ratio
        public UIImage MaxResizeImage (UIImage sourceImage, float maxWidth, float maxHeight)
        {
            var sourceSize = sourceImage.Size;
            var maxResizeFactor = Math.Max (maxWidth / sourceSize.Width, maxHeight / sourceSize.Height);
            if (maxResizeFactor > 1) return sourceImage;
            var width = maxResizeFactor * sourceSize.Width;
            var height = maxResizeFactor * sourceSize.Height;
            UIGraphics.BeginImageContext (new SizeF ((float)width, (float)height));
            sourceImage.Draw (new RectangleF (0, 0, (float)width, (float)height));
            var resultImage = UIGraphics.GetImageFromCurrentImageContext ();
            UIGraphics.EndImageContext ();
            return resultImage;
        }

如何在你的代码上使用

Camera.TakePicture(this, (obj) =>
            {
                var photo = obj.ValueForKey(new NSString("UIImagePickerControllerOriginalImage")) as UIImage;
                var image = MaxResizeImage (photo,1280, 720);
                Byte[] myByteArray;
                using (NSData imageData = image.AsJPEG(0.0f))
                {

                    myByteArray = new Byte[imageData.Length];
                    System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, myByteArray, 0, Convert.ToInt32(imageData.Length));
                }

            }); 

关于ios - 如何缩小iphone 7中相机拍摄的照片的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43974553/

相关文章:

ios - 无需导航即可更改 View

iphone - NSOperationQueue阻止了不相关的NSOperationQueue?

ios - 是否可以在没有 Core Data 关系的情况下获取对象?

java - netbeans-如何使用Restful webservice的.war文件?

c# - Xamarin iOS 应用程序中的反序列化需要时间

iphone - 声音不使用 AVAudioPlayer 播放

mysql - 在 Asp .net Web API 中使用交叉连接出现错误

asp.net - 打开 Windows 身份验证时使用 ajax 调用 Web 服务?

ios - 不能将多个 UIBarButtonItem 添加到 RightBarButtonItems

c# - 如何在跨平台应用程序之间共享 SQLite 代码?