Пример #1
0
        private Bitmap GetThunbailFromVideo(string filename, ThumbnailKind ScreenKind)
        {
            Bitmap thumb = ThumbnailUtils.CreateVideoThumbnail(filename,
                                                               ScreenKind);

            return(RotateBitmap(thumb, 90));
        }
Пример #2
0
    public static float[] getPixels(Bitmap bitmap)
    {
        if (((bitmap.Width != IMAGE_SIZE) ||
             (bitmap.Height != IMAGE_SIZE)))
        {
            //  rescale the bitmap if needed
            bitmap = ThumbnailUtils.ExtractThumbnail(bitmap, IMAGE_SIZE, IMAGE_SIZE);
        }

        int[] intValues = new int[(IMAGE_SIZE * IMAGE_SIZE)];
        bitmap.GetPixels(intValues, 0, bitmap.Width, 0, 0, bitmap.Width, bitmap.Height);
        float[] floatValues = new float[(IMAGE_SIZE
                                         * (IMAGE_SIZE * 3))];
        //  Preprocess the image data from 0-255 int to normalized float based
        //  on the provided parameters.
        for (int i = 0; (i < intValues.Length); i++)
        {
            int val = intValues[i];
            floatValues[(i * 3)] = ((((val + 16)
                                      & 255)
                                     - IMAGE_MEAN)
                                    / IMAGE_STD);
            floatValues[((i * 3)
                         + 1)] = ((((val + 8)
                                    & 255)
                                   - IMAGE_MEAN)
                                  / IMAGE_STD);
            floatValues[((i * 3)
                         + 2)] = (((val & 255)
                                   - IMAGE_MEAN)
                                  / IMAGE_STD);
        }

        return(floatValues);
    }
        public byte[] GetVideoThumbnail(string path)
        {
            try
            {
                Bitmap bmThumbnail = ThumbnailUtils.CreateVideoThumbnail(path, ThumbnailKind.FullScreenKind);

                byte[] bitmapData;
                using (var stream = new MemoryStream())
                {
                    bmThumbnail.Compress(Bitmap.CompressFormat.Png, 0, stream);
                    bitmapData = stream.ToArray();
                }

                //ByteArrayOutputStream stream = new ByteArrayOutputStream();
                //bmThumbnail.Compress(Bitmap.CompressFormat.Png, 100, stream.);
                //byte[] byteArray = stream.ToByteArray();
                return(bitmapData);
            }
            catch (Exception e)
            {
                //Console.WriteLine(e);
            }
            // // MINI_KIND: 512 x 384 thumbnail
            // bmThumbnail = ThumbnailUtils.createVideoThumbnail(filePath,
            //MediaStore.Video.Thumbnails.MINI_KIND);
            // thumbnail_mini.setImageBitmap(bmThumbnail);


            return(null);
        }
Пример #4
0
        /**
         *           * @param imagePath
         *           *   图像的路径
         *           * @param width
         *           *   指定输出图像的宽度
         *           * @param height
         *           *   指定输出图像的高度
         *           * @return 生成的缩略图
         *           */
        public static Bitmap GetImageThumbnail(string imagePath, int width, int height)
        {
            Bitmap bitmap = null;

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.InJustDecodeBounds = true;
            // 获取这个图片的宽和高,注意此处的bitmap为null
            bitmap = BitmapFactory.DecodeFile(imagePath, options);
            options.InJustDecodeBounds = false; // 设为 false
                                                // 计算缩放比
            int h        = options.OutHeight;
            int w        = options.OutWidth;
            int beWidth  = w / width;
            int beHeight = h / height;
            int be       = 1;

            if (beWidth < beHeight)
            {
                be = beWidth;
            }
            else
            {
                be = beHeight;
            }
            if (be <= 0)
            {
                be = 1;
            }
            options.InSampleSize = be;
            // 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false
            bitmap = BitmapFactory.DecodeFile(imagePath, options);
            // 利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个Bitmap对象
            bitmap = ThumbnailUtils.ExtractThumbnail(bitmap, width, height, ThumnailExtractOptions.RecycleInput);
            return(bitmap);
        }
Пример #5
0
        async Task <Bitmap> PortableAsyncRenderer <Bitmap> .GetThumbnailAsync
        (
            PortableCorrelatedEntity correlatedEntity,
            Func <string> correlationTag,
            int viewWidth,
            int viewHeight//,
            //Bitmap reusedThumbnail
        )
        {
            if (correlatedEntity.CorrelationTag != correlationTag())
            {
                return(null);
            }

            Task <Bitmap> thumbnailTask = ThumbnailUtils.CreateVideoThumbnailAsync
                                          (
                FilePath,
                ThumbnailKind.MicroKind
                                          );

            if (thumbnailTask.Result == null)
            {
                throw new CorruptObjectException(FileName);
            }

            return(await thumbnailTask);
        }
Пример #6
0
        /**
         *   * 获取视频的缩略图 先通过ThumbnailUtils来创建一个视频的缩略图,然后再利用ThumbnailUtils来生成指定大小的缩略图。
         *   * 如果想要的缩略图的宽和高都小于MICRO_KIND,则类型要使用MICRO_KIND作为kind的值,这样会节省内存。
         *   *
         *   * @param videoPath
         *   *   视频的路径
         *   * @param width
         *   *   指定输出视频缩略图的宽度
         *   * @param height
         *   *   指定输出视频缩略图的高度度
         *   * @param kind
         *   *   参照MediaStore.Images.Thumbnails类中的常量MINI_KIND和MICRO_KIND。
         *   *   其中,MINI_KIND: 512 x 384,MICRO_KIND: 96 x 96
         *   * @return 指定大小的视频缩略图
         *   */
        public static Bitmap GetVideoThumbnail(String videoPath, int width, int height, ThumbnailKind kind)
        {
            Bitmap bitmap = null;

            bitmap = ThumbnailUtils.CreateVideoThumbnail(videoPath, kind);
            bitmap = ThumbnailUtils.ExtractThumbnail(bitmap, width, height, ThumnailExtractOptions.RecycleInput);
            return(bitmap);
        }
Пример #7
0
        /// <summary>
        /// Downscales a bitmap by the specified factor
        /// </summary>
        /// <returns>The bitmap.</returns>
        /// <param name="wallpaper">Wallpaper.</param>
        /// <param name="factor">Factor.</param>
        public static Bitmap downscaleBitmap(Bitmap wallpaper, int factor)
        {
            // convert to bitmap and get the center
            int widthPixels  = wallpaper.Width / factor;
            int heightPixels = wallpaper.Height / factor;

            return(ThumbnailUtils.ExtractThumbnail(wallpaper, widthPixels, heightPixels));
        }
        private MediaModel CreateMediaModel(Android.Net.Uri oUri)
        {
            MediaModel oModel = null;
            var        oType  = CrossCurrentActivity.Current.Activity.ContentResolver.GetType(oUri);

            var oPath = GetPathUri(oUri);

            if (oPath != null)
            {
                string        sPath          = string.Empty;
                string        sThumpnailPath = string.Empty;
                string        sFileName      = System.IO.Path.GetFileName(oPath);
                string        sExt           = System.IO.Path.GetExtension(oPath) ?? string.Empty;
                MediaFileType mediaFileType  = MediaFileType.Image;



                if (oType.StartsWith(Enum.GetName(typeof(MediaFileType), MediaFileType.Image), StringComparison.CurrentCultureIgnoreCase))
                {
                    var fullImage = ImageHelper.RotateImage(oPath, 1);

                    sPath = FileService.GetOutputPath(MediaFileType.Image, TempDir, $"{sFileName}{sExt}");
                    File.WriteAllBytes(sPath, fullImage);

                    var oThumpnailImg = ImageHelper.RotateImage(oPath, 0.25f);
                    sThumpnailPath = FileService.GetOutputPath(MediaFileType.Image, TempDir, $"{sFileName}-THUMBNAIL{sExt}");

                    File.WriteAllBytes(sThumpnailPath, oThumpnailImg);
                }
                else if (oType.StartsWith(Enum.GetName(typeof(MediaFileType), MediaFileType.Video), StringComparison.CurrentCultureIgnoreCase))
                {
                    sPath = oPath;
                    var bitmap = ThumbnailUtils.CreateVideoThumbnail(oPath, ThumbnailKind.MiniKind);

                    sThumpnailPath = FileService.GetOutputPath(MediaFileType.Image, TempDir, $"{sFileName}-THUMBNAIL{sExt}");
                    var stream = new FileStream(sThumpnailPath, FileMode.Create);
                    bitmap?.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
                    stream.Close();

                    mediaFileType = MediaFileType.Video;
                }

                if (!string.IsNullOrEmpty(sPath) && !string.IsNullOrEmpty(sThumpnailPath))
                {
                    oModel = new MediaModel()
                    {
                        FilePath    = sPath,
                        MediaType   = mediaFileType,
                        PreviewFile = sThumpnailPath
                    };
                }
            }


            return(oModel);
        }
        internal static async Task <StorageItemThumbnail> CreateVideoThumbnailAsync(StorageFile file)
        {
            var bmp = await ThumbnailUtils.CreateVideoThumbnailAsync(file.Path, Android.Provider.ThumbnailKind.MiniKind);

            MemoryStream stream = new MemoryStream();
            await bmp.CompressAsync(Bitmap.CompressFormat.Jpeg, 90, stream);

            stream.Seek(0, SeekOrigin.Begin);
            return(new StorageItemThumbnail(stream));
        }
        internal static async Task <StorageItemThumbnail> CreatePhotoThumbnailAsync(StorageFile file)
        {
            var bmp = await ThumbnailUtils.ExtractThumbnailAsync(await BitmapFactory.DecodeFileAsync(file.Path), 240, 240, ThumnailExtractOptions.None);

            MemoryStream stream = new MemoryStream();
            await bmp.CompressAsync(Bitmap.CompressFormat.Jpeg, 90, stream);

            stream.Seek(0, SeekOrigin.Begin);
            return(new StorageItemThumbnail(stream));
        }
Пример #11
0
        MediaFile CreateMediaFileFromUri(Android.Net.Uri uri)
        {
            MediaFile mediaFile = null;
            var       type      = CrossCurrentActivity.Current.Activity.ContentResolver.GetType(uri);

            var path = GetRealPathFromURI(uri);

            if (path != null)
            {
                string        fullPath           = string.Empty;
                string        thumbnailImagePath = string.Empty;
                var           fileName           = System.IO.Path.GetFileNameWithoutExtension(path);
                var           ext           = System.IO.Path.GetExtension(path) ?? string.Empty;
                MediaFileType mediaFileType = MediaFileType.Image;
                var           imageTypeName = Enum.GetName(typeof(MediaFileType), MediaFileType.Image).ToLowerInvariant();
                var           videoTypeName = Enum.GetName(typeof(MediaFileType), MediaFileType.Video).ToLowerInvariant();

                if (type.ToLower().StartsWith(imageTypeName, StringComparison.CurrentCultureIgnoreCase))
                {
                    var fullImage  = ImageHelpers.RotateImage(path, 1);
                    var thumbImage = ImageHelpers.RotateImage(path, 0.25f);


                    fullPath = FileHelper.GetOutputPath(MediaFileType.Image, TemporalDirectoryName, $"{fileName}{ext}");
                    File.WriteAllBytes(fullPath, fullImage);

                    thumbnailImagePath = FileHelper.GetOutputPath(MediaFileType.Image, TemporalDirectoryName, $"{fileName}-THUMBNAIL{ext}");
                    File.WriteAllBytes(thumbnailImagePath, thumbImage);
                }
                else if (type.ToLowerInvariant().StartsWith(videoTypeName, StringComparison.CurrentCultureIgnoreCase))
                {
                    fullPath = path;
                    var bitmap = ThumbnailUtils.CreateVideoThumbnail(path, ThumbnailKind.MiniKind);

                    thumbnailImagePath = FileHelper.GetOutputPath(MediaFileType.Image, TemporalDirectoryName, $"{fileName}-THUMBNAIL{ext}");
                    var stream = new FileStream(thumbnailImagePath, FileMode.Create);
                    bitmap?.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
                    stream.Close();

                    mediaFileType = MediaFileType.Video;
                }

                if (!string.IsNullOrEmpty(fullPath) && !string.IsNullOrEmpty(thumbnailImagePath))
                {
                    mediaFile = new MediaFile()
                    {
                        Path        = fullPath,
                        Type        = mediaFileType,
                        PreviewPath = thumbnailImagePath
                    };
                }
            }

            return(mediaFile);
        }
Пример #12
0
        private async Task LoadThumbIntoImageList(string imagePath, Activity context)
        {
            Bitmap thumb = await ThumbnailUtils.CreateVideoThumbnailAsync(imagePath, ThumbnailKind.MiniKind);
            ImageViewAsync newImage = new ImageViewAsync(context);
            newImage.SetPadding(10, 10, 10, 10);

            ItemList.AddView(newImage);
            newImage.SetImageBitmap(thumb);

            newImage.Click += Item_Click;
        }
Пример #13
0
        public ImageSource GetVideoThumbnail(string url)
        {
            Bitmap thumb  = ThumbnailUtils.CreateVideoThumbnail(url, ThumbnailKind.MiniKind);
            var    imgsrc = ImageSource.FromStream(() =>
            {
                MemoryStream ms = new MemoryStream();
                thumb.Compress(Bitmap.CompressFormat.Jpeg, 100, ms);
                ms.Seek(0L, SeekOrigin.Begin);
                return(ms);
            });

            return(imgsrc);
        }
Пример #14
0
        private async void LoadThumbnail(ViewHolder viewHolder, int position)
        {
            var content = GetItemAt(position);

            var bitmap = await BitmapFactory.DecodeFileAsync(content.Path);

            var thumbnail = await ThumbnailUtils.ExtractThumbnailAsync(bitmap, viewHolder.PreviewImage.Width, viewHolder.PreviewImage.Height);

            if (position == (int)viewHolder.ItemView.Tag)
            {
                viewHolder.PreviewImage.SetImageBitmap(thumbnail);
            }
        }
Пример #15
0
    /// <inheritdoc />
    protected override async Task <bool> Render(
        ThumbnailsRenderContext ctx,
        ThumbnailsRenderFileInfo fileInfo,
        ThumbnailsRenderOption option)
    {
        // use the following code maybe faster. https://github.com/kleisauke/net-vips/issues/128
        // > sourceVipsImage = Image.Thumbnail(localPath, loadImageSize, loadImageSize, noRotate: false);
        return(await _fileService.ReadFileStream(
                   fileInfo.FileHandle,
                   stream =>
        {
            var sourceVipsImage = Image.ThumbnailStream(
                stream,
                (int)(ThumbnailUtils.DefaultMaxWidth * ctx.Density),
                height: (int)(ThumbnailUtils.DefaultMaxHeight * ctx.Density),
                noRotate: false);

            sourceVipsImage = sourceVipsImage.Colourspace(Enums.Interpretation.Srgb).Cast(Enums.BandFormat.Uchar);
            if (!sourceVipsImage.HasAlpha())
            {
                sourceVipsImage = sourceVipsImage.Bandjoin(255);
            }

            var imageWidth = sourceVipsImage.Width;
            var imageHeight = sourceVipsImage.Height;

            var sourceImageDataPtr = sourceVipsImage.WriteToMemory(out _);
            sourceVipsImage.Close();

            try
            {
                using var colorspace = SKColorSpace.CreateSrgb();
                var sourceImageInfo = new SKImageInfo(
                    imageWidth,
                    imageHeight,
                    SKColorType.Rgba8888,
                    SKAlphaType.Unpremul,
                    colorspace);

                using var image =
                          SKImage.FromPixels(sourceImageInfo, sourceImageDataPtr, sourceImageInfo.RowBytes);
                ThumbnailUtils.DrawShadowView(ctx, new SkImageView(image));
            }
            finally
            {
                NetVips.NetVips.Free(sourceImageDataPtr);
            }

            return ValueTask.FromResult(true);
        }));
    }
Пример #16
0
        protected override Bitmap Load(Android.Content.Context _context, long id)
        {
            var uri = IdToUri(id);


            using (var inputStream = _context.ContentResolver.OpenInputStream(uri))
            {
                var    bitmap     = BitmapFactory.DecodeStream(inputStream, null, null);
                Bitmap ThumbImage = ThumbnailUtils.ExtractThumbnail(bitmap, MinSide, MinSide);

                bitmap.Recycle();
                bitmap.Dispose();

                return(ThumbImage);
            }
        }
        public byte[] ResizeImage(byte[] imageBytes, int newWidth, int newHeight)
        {
            Byte[] NewByteArray = null;

            // byte[] -> bitmap
            using (var image = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length)) {
                using (var bitmap = ThumbnailUtils.ExtractThumbnail(image, newWidth, newHeight)) {
                    // bitmap -> byte[]
                    MemoryStream stream = new MemoryStream();
                    bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
                    NewByteArray = stream.ToArray();
                }
            }

            return(NewByteArray);
        }
Пример #18
0
    private static void DrawAttachedPicture(ThumbnailsRenderContext ctx, MediaStream attachedPicStream)
    {
        using var attachedPicture = attachedPicStream.ReadAttachedPicture();
        var attachedPictureVipsImage = Image.ThumbnailStream(
            attachedPicture,
            (int)(ThumbnailUtils.DefaultMaxWidth * ctx.Density),
            height: (int)(ThumbnailUtils.DefaultMaxHeight * ctx.Density),
            noRotate: false);

        attachedPictureVipsImage = attachedPictureVipsImage.Colourspace(Enums.Interpretation.Srgb).Cast(Enums.BandFormat.Uchar);
        if (!attachedPictureVipsImage.HasAlpha())
        {
            attachedPictureVipsImage = attachedPictureVipsImage.Bandjoin(255);
        }

        var imageWidth  = attachedPictureVipsImage.Width;
        var imageHeight = attachedPictureVipsImage.Height;

        var sourceImageDataPtr = attachedPictureVipsImage.WriteToMemory(out _);

        attachedPictureVipsImage.Close();

        try
        {
            using var colorspace = SKColorSpace.CreateSrgb();
            var sourceImageInfo = new SKImageInfo(
                imageWidth,
                imageHeight,
                SKColorType.Rgba8888,
                SKAlphaType.Unpremul,
                colorspace);

            using var image =
                      SKImage.FromPixels(sourceImageInfo, sourceImageDataPtr, sourceImageInfo.RowBytes);
            _cachedDecorationImage ??= SKImage.FromEncodedData(ReadDecorationImage());
            ThumbnailUtils.DrawShadowView(
                ctx,
                new SkImageView(image),
                _cachedDecorationImage,
                new SKColor(0, 0, 0),
                minSize: new SKSize(24, 24));
        }
        finally
        {
            NetVips.NetVips.Free(sourceImageDataPtr);
        }
    }
        public System.IO.Stream GetThumbnail(string pathMediaPath)
        {
            try {
                Bitmap thumb = ThumbnailUtils.CreateVideoThumbnail(pathMediaPath, ThumbnailKind.FullScreenKind);

                System.IO.Stream stream = new MemoryStream();
                thumb.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
                stream.Seek(0L, SeekOrigin.Begin);

                return(stream);
            }
            catch (Exception exc) {
                Debugger.Break();

                return(null);
            }
        }
Пример #20
0
        private async void FixMissing()
        {
            List <string> missing = new List <string>();

            //look in fixing dir
            DirSearch(GetExternalPath() + "/missing", missing);

            await Bootlegger.BootleggerClient.OfflineConnect(CurrentEvent.id, cancel.Token);

            //for each, create new clip
            foreach (var file in missing)
            {
                FileInfo ff       = new FileInfo(file);
                var      filename = ff.Name;
                var      group    = ff.Directory.Name;

                //generate thumbnail
                Bootlegger.BootleggerClient.CurrentClientRole = Bootlegger.BootleggerClient.CurrentEvent.roles.First();
                //var ev = await Bootlegger.BootleggerClient.GetEventInfo(CurrentEvent.id,new CancellationTokenSource().Token);
                Bootlegger.BootleggerClient.SetShot(Bootlegger.BootleggerClient.CurrentClientRole.Shots.First());

                Dictionary <string, string> meta = new Dictionary <string, string>();

                try
                {
                    FileStream outt;
                    var        bitmap = await ThumbnailUtils.CreateVideoThumbnailAsync(file, Android.Provider.ThumbnailKind.MiniKind);

                    outt = new FileStream(file + ".jpg", FileMode.CreateNew);
                    await bitmap.CompressAsync(Android.Graphics.Bitmap.CompressFormat.Jpeg, 90, outt);

                    outt.Close();
                }
                catch
                {
                }


                meta.Add("captured_at", ff.CreationTime.ToString("dd/MM/yyyy H:mm:ss.ff tt zz"));
                MediaItem newm = new MediaItem();
                newm.Filename = file;
                //add to upload queue (for the right user)
                var mediaitem = Bootlegger.BootleggerClient.CreateMediaMeta(newm, meta, null, file + ".jpg");
                Bootlegger.BootleggerClient.UnSelectRole(!WhiteLabelConfig.REDUCE_BANDWIDTH, true);
            }
        }
Пример #21
0
        private async Task <string> SaveThumbnailToFileAsync(string path)
        {
            return(await Task.Run(() =>
            {
                string thumbnailPath;

                var bmThumbnail = ThumbnailUtils.CreateVideoThumbnail(path, ThumbnailKind.MiniKind);
                if (bmThumbnail != null)
                {
                    thumbnailPath = SaveToFile(path, bmThumbnail);
                }
                else
                {
                    // TODO : Default Thumbnail Image
                    thumbnailPath = String.Empty;
                }

                return thumbnailPath;
            }));
        }
Пример #22
0
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            ViewHolder holder;
            var        item = selectedImage[position];

            if (convertView == null)
            {
                convertView         = activity.LayoutInflater.Inflate(Resource.Layout.SelectImageItem, parent, false);
                holder              = new ViewHolder();
                holder.ivEventPhoto = convertView.FindViewById <ImageView>(Resource.Id.ivSelectedItemEventPhoto);
                holder.ivEventVideo = convertView.FindViewById <ImageView>(Resource.Id.ivSelectItem_video);
                convertView.Tag     = holder;
            }
            else
            {
                holder = convertView.Tag as ViewHolder;
            }
            Bitmap thumb = null;

            holder.ivEventPhoto.SetImageResource(0);

            if (type == 1)
            {
                holder.ivEventVideo.Visibility = ViewStates.Visible;
                thumb = ThumbnailUtils.CreateVideoThumbnail(item, Android.Provider.ThumbnailKind.MiniKind);
                if (thumb != null)
                {
                    holder.ivEventPhoto.SetImageBitmap(thumb);
                }
            }
            else
            {
                Picasso.With(activity).Load(new Java.IO.File(item)).Placeholder(Resource.Drawable.default_event_back)
                .Transform(new RoundedTransformation())
                .Resize(150, 150).Into(holder.ivEventPhoto);
                holder.ivEventVideo.Visibility = ViewStates.Gone;
            }
            // Dispose of the Java side bitmap.
            return(convertView);
        }
Пример #23
0
        public static Bitmap cropCenter(Bitmap bmp, int width = 160, int height = 120)
        {
            bool portrait = bmp.Width < bmp.Height;

            if (portrait)
            {
                int x = width;
                width  = height;
                height = x;
            }

            Bitmap result = null;

            try
            {
                result = ThumbnailUtils.ExtractThumbnail(bmp, width, height);
            }
            catch (System.Exception)
            {
            }
            return(result);
        }
        public static string CreateThumbnail(string sourceFile, int reqWidth, int reqHeight, string thumbnailPrefix = "")
        {
            var thumbnail = sourceFile.Replace(".jpg", $"_{thumbnailPrefix}thumb.jpg");

            var source = sourceFile.LoadBitmap();
            var target = ThumbnailUtils.ExtractThumbnail(source, reqWidth, reqHeight);

            using (var outStream = System.IO.File.Create(thumbnail))
            {
                if (thumbnail.ToLower().EndsWith("png"))
                {
                    target.Compress(Bitmap.CompressFormat.Png, 100, outStream);
                }
                else
                {
                    target.Compress(Bitmap.CompressFormat.Jpeg, 95, outStream);
                }
            }
            source.Recycle();
            target.Recycle();
            return(thumbnail);
        }
Пример #25
0
        static public async Task <ImageType> LoadPictureFromData(byte[] data, bool thumbnail)
        {
            Bitmap bmp = null;

            if (thumbnail)
            {
                using (var stream = new MemoryStream(data))
                {
                    using (var first = await BitmapFactory.DecodeStreamAsync(stream))
                        bmp = ThumbnailUtils.ExtractThumbnail(first, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
                }
            }
            else
            {
                using (var stream = new MemoryStream(data))
                    bmp = await BitmapFactory.DecodeStreamAsync(stream);
            }
            if (bmp == null)
            {
                Insight.Track(string.Format("LoadPictureFromData returning NULL dataSize:{0}, thumbnail:{1}", data.Length, thumbnail));
            }
            return(bmp);
        }
Пример #26
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (resultCode == Result.Ok)
            {
                if (requestCode == REQUEST_TAKE_GALLERY_VIDEO)
                {
                    horizontal_recycler_view.Visibility = ViewStates.Visible;
                    var    uri  = data.Data;
                    string path = BasicUtils.GetActualPathFromFile(uri, this);
                    System.Diagnostics.Debug.WriteLine("Image path == " + path);
                    Bitmap thumb = ThumbnailUtils.CreateVideoThumbnail(path, ThumbnailKind.MiniKind);

                    AddUpdateImageModel addUpdateImage = new AddUpdateImageModel();
                    base64ImageCode = BasicUtils.GetInstance().ConvertBitmapToBase64(thumb);


                    addUpdateImage.bitmap     = thumb;
                    addUpdateImage.ImageUrl   = base64ImageCode;
                    addUpdateImage.CountImage = imagesList.Count + 1;
                    imagesList.Add(addUpdateImage);
                    addUpdateImageAdapter.NotifyDataSetChanged();
                    horizontal_recycler_view.SmoothScrollToPosition(imagesList.Count());
                }
                if (requestCode == CameraCaptureImageRequestCode)
                {
                    PreviewCapturedImage();
                }
                else if (requestCode == CameraCaptureVideoRequestCode)
                {
                    horizontal_recycler_view.Visibility = ViewStates.Visible;
                    var    uri  = data.Data;
                    string path = BasicUtils.GetActualPathFromFile(uri, this);
                    System.Diagnostics.Debug.WriteLine("Image path == " + path);
                    Bitmap thumb = ThumbnailUtils.CreateVideoThumbnail(path, ThumbnailKind.MiniKind);

                    AddUpdateImageModel addUpdateImage = new AddUpdateImageModel();
                    base64ImageCode = BasicUtils.GetInstance().ConvertBitmapToBase64(thumb);


                    addUpdateImage.bitmap     = thumb;
                    addUpdateImage.ImageUrl   = base64ImageCode;
                    addUpdateImage.CountImage = imagesList.Count + 1;
                    imagesList.Add(addUpdateImage);
                    addUpdateImageAdapter.NotifyDataSetChanged();
                    horizontal_recycler_view.SmoothScrollToPosition(imagesList.Count());
                }
                else if (requestCode == PicFromGallery)
                {
                    fileUri = data.Data;

                    Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, fileUri);


                    GetImageFromGallery();
                }
                else if (requestCode == PicCrop && data != null)
                {
                    //get the returned data
                    Android.Net.Uri extras = data.Data;
                    //get the cropped bitmap

                    if (extras != null)
                    {
                        var inp = context.ContentResolver.OpenInputStream(extras);
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        Bitmap cropped_bitmap         = BitmapFactory.DecodeStream(inp, null, options);
                        newBitmap = cropped_bitmap;
                        getImageBitmapAsync(newBitmap);
                    }
                    else
                    {
                        var inp = context.ContentResolver.OpenInputStream(fileUri);
                        BitmapFactory.Options options = new BitmapFactory.Options();


                        //Bitmap cropped_bitmap =
                        MemoryStream stream = new MemoryStream();
                        BitmapFactory.DecodeStream(inp, null, options).Compress(Bitmap.CompressFormat.Jpeg, 50, stream);

                        byte[] bitmapData = stream.ToArray();
                        Bitmap bitmap     = BitmapFactory.DecodeByteArray(bitmapData, 0, bitmapData.Length);


                        newBitmap = bitmap;
                        getImageBitmapAsync(newBitmap);
                    }
                }
            }
        }
        public static async Task <Bitmap> createVideoBitmapAsync(int width, int height, string videoFilePath)
        {
            Bitmap videoThumbnail = await ThumbnailUtils.CreateVideoThumbnailAsync(videoFilePath, ThumbnailKind.MicroKind);

            return(Bitmap.CreateScaledBitmap(videoThumbnail, width, height, false));
        }
Пример #28
0
    private static unsafe void DrawWaves(ThumbnailsRenderContext ctx, MediaStream audioStream)
    {
        var height = 88;
        var width  = 88;

        using var recorder = new SKPictureRecorder();
        using var canvas   = recorder.BeginRecording(SKRect.Create(width, height));
        var columnCount = 88 * 2;
        var columnWidth = (float)width / columnCount;

        using var wavePaint = new SKPaint { Color = new SKColor(128, 128, 128, 76), StrokeWidth = columnWidth };
        var totalSample     = audioStream.SampleRate * audioStream.Duration;
        var columnMaxSample = (int)(totalSample / columnCount);
        var columns         = new short[columnCount];

        using var decoder = audioStream.CreateStreamDecoder();
        using var filter  = new AudioFormatFilter("sample_fmts=s16:channel_layouts=mono", audioStream, decoder);
        filter.Build();

        long sum = 0;
        var  n   = 0;
        var  c   = 0;

        while (filter.MoveNext())
        {
            var frame = filter.Current.Value;
            var p     = (short *)frame->data[0];

            for (var i = 0; i < frame->nb_samples; i++)
            {
                sum += SampleAbs(p[i]);

                n++;
                if (n == columnMaxSample && c < columnCount)
                {
                    columns[c] = (short)(sum / n);

                    n   = 0;
                    sum = 0;
                    c++;
                }
            }
        }

        for (var i = 0; i < columnCount; i++)
        {
            var h = Math.Max((float)columns[i] * height / short.MaxValue, 0.5f);
            var x = i * columnWidth;
            canvas.DrawLine(x, (height - h) / 2.0f, x, (height + h) / 2.0f, wavePaint);
        }

        _cachedWaveformDecorationImage ??= SKImage.FromEncodedData(ReadWaveformDecorationImage());
        canvas.DrawImage(_cachedWaveformDecorationImage, SKRect.Create((width - 28) / 2.0f, (height - 36) / 2.0f, 28, 36));

        using var picture = recorder.EndRecording();
        ThumbnailUtils.DrawShadowView(
            ctx,
            new SkPictureView(
                picture,
                new SKSize(88, 88)));
    }
        MediaFile CreateMediaFileFromUri(Android.Net.Uri uri)
        {
            MediaFile mediaFile = null;
            var       type      = CrossCurrentActivity.Current.Activity.ContentResolver.GetType(uri);

            var path = GetRealPathFromURI(uri);

            if (path != null)
            {
                string        fullPath           = string.Empty;
                string        thumbnailImagePath = string.Empty;
                string        onbaseImagePath    = string.Empty;
                var           fileName           = System.IO.Path.GetFileNameWithoutExtension(path);
                var           ext           = System.IO.Path.GetExtension(path) ?? string.Empty;
                MediaFileType mediaFileType = MediaFileType.Image;

                if (type.StartsWith(Enum.GetName(typeof(MediaFileType), MediaFileType.Image), StringComparison.CurrentCultureIgnoreCase))
                {
                    string watermark   = Globals.IncluirWatermarkEnFotosGalería ? WatermarkHelper.ArmaWatermark() : null;
                    var    fullImage   = ImageHelpers.RotateImage(path, 1, 90, watermark);
                    var    thumbImage  = ImageHelpers.RotateImage(path, 0.25f, 90);
                    var    onbaseImage = ImageHelpers.RotateImage(path, 1, Globals.PorcentajeCompresion, watermark);

                    fullPath = FileHelper.GetOutputPath(MediaFileType.Image, TemporalDirectoryName, $"{fileName}{ext}");
                    File.WriteAllBytes(fullPath, fullImage);

                    thumbnailImagePath = FileHelper.GetOutputPath(MediaFileType.Image, TemporalDirectoryName, $"{fileName}-THUMBNAIL{ext}");
                    File.WriteAllBytes(thumbnailImagePath, thumbImage);

                    onbaseImagePath = FileHelper.GetOutputPath(MediaFileType.Image, TemporalDirectoryName, $"{fileName}-ONBASE{ext}");
                    File.WriteAllBytes(onbaseImagePath, onbaseImage);
                }
                else if (type.StartsWith(Enum.GetName(typeof(MediaFileType), MediaFileType.Video), StringComparison.CurrentCultureIgnoreCase))
                {
                    fullPath = path;
                    var bitmap = ThumbnailUtils.CreateVideoThumbnail(path, ThumbnailKind.MiniKind);

                    thumbnailImagePath = FileHelper.GetOutputPath(MediaFileType.Image, TemporalDirectoryName, $"{fileName}-THUMBNAIL{ext}");
                    var stream = new FileStream(thumbnailImagePath, FileMode.Create);
                    bitmap?.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
                    stream.Close();

                    mediaFileType = MediaFileType.Video;
                }

                if (!string.IsNullOrEmpty(fullPath) &&
                    !string.IsNullOrEmpty(thumbnailImagePath) &&
                    !string.IsNullOrEmpty(onbaseImagePath))
                {
                    mediaFile = new MediaFile()
                    {
                        Id          = System.Guid.NewGuid().ToString(),
                        Path        = fullPath,
                        Type        = mediaFileType,
                        PreviewPath = thumbnailImagePath,
                        OnBasePath  = onbaseImagePath
                    };
                }
            }

            return(mediaFile);
        }
Пример #30
0
        async Task <FileData> GetFileData(Android.Net.Uri p_uri)
        {
            var filePath = IOUtil.GetPath(_context, p_uri);

            if (string.IsNullOrEmpty(filePath))
            {
                filePath = IOUtil.IsMediaStore(p_uri.Scheme) ? p_uri.ToString() : p_uri.Path;
            }
            var fileName = GetFileName(_context, p_uri);

            var    fd  = new FileData(filePath, fileName, (ulong)new File(filePath).Length());
            string ext = fd.Ext;

            // 生成文件描述和缩略图
            if (FileFilter.UwpImage.Contains(ext))
            {
                BitmapFactory.Options options = new BitmapFactory.Options();
                // 只解析图片大小,不加载内容
                options.InJustDecodeBounds = true;
                BitmapFactory.DecodeFile(filePath, options);
                fd.Desc = $"{options.OutWidth} x {options.OutHeight} ({ext.TrimStart('.')})";

                int maxSize = Math.Max(options.OutWidth, options.OutHeight);
                if (maxSize > FileData.ThumbSize)
                {
                    // 直接按缩放比例加载
                    options.InJustDecodeBounds = false;
                    options.InSampleSize       = maxSize / FileData.ThumbSize;
                    // v29 弃用
                    //options.InPurgeable = true;
                    Bitmap bmp = BitmapFactory.DecodeFile(filePath, options);

                    fd.ThumbPath = System.IO.Path.Combine(Kit.CachePath, Kit.NewGuid + "-t.jpg");
                    using (var fs = System.IO.File.Create(fd.ThumbPath))
                    {
                        await bmp.CompressAsync(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, fs);
                    }
                    bmp.Recycle();
                }
            }
            else if (FileFilter.UwpVideo.Contains(ext))
            {
                Android.Media.MediaMetadataRetriever media = new Android.Media.MediaMetadataRetriever();
                try
                {
                    await media.SetDataSourceAsync(filePath);

                    string dur    = media.ExtractMetadata(Android.Media.MetadataKey.Duration);
                    string width  = media.ExtractMetadata(Android.Media.MetadataKey.VideoWidth);
                    string height = media.ExtractMetadata(Android.Media.MetadataKey.VideoHeight);
                    fd.Desc = string.Format("{0:HH:mm:ss} ({1} x {2})", new DateTime(long.Parse(dur) * 10000), width, height);
                }
                catch { }
                finally
                {
                    media.Release();
                }

                // 帧缩略图
                var bmp = await ThumbnailUtils.CreateVideoThumbnailAsync(filePath, ThumbnailKind.MiniKind);

                fd.ThumbPath = System.IO.Path.Combine(Kit.CachePath, Kit.NewGuid + "-t.jpg");
                using (var fs = System.IO.File.Create(fd.ThumbPath))
                {
                    await bmp.CompressAsync(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, fs);
                }
                bmp.Recycle();
            }
            else if (FileFilter.UwpAudio.Contains(ext))
            {
                Android.Media.MediaMetadataRetriever media = new Android.Media.MediaMetadataRetriever();
                try
                {
                    await media.SetDataSourceAsync(filePath);

                    string dur = media.ExtractMetadata(Android.Media.MetadataKey.Duration);
                    fd.Desc = string.Format("{0:mm:ss}", new DateTime(long.Parse(dur) * 10000));
                }
                catch { }
                finally
                {
                    media.Release();
                }
            }
            return(fd);
        }