Ejemplo n.º 1
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);
        }
Ejemplo n.º 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);
    }
Ejemplo n.º 3
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);
        }
Ejemplo n.º 4
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));
        }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 9
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);
        }
        public static void GenerateImageThumbnail(string imageName, string thumbnailName, int width, int height, int type)
        {
            System.IO.FileStream os = null;
            try
            {
                Bitmap bmp = null;
                BitmapFactory.Options ops = new BitmapFactory.Options();
                ops.InJustDecodeBounds = true;
                bmp = BitmapFactory.DecodeFile(imageName, ops);

                ops.InJustDecodeBounds = false;
                // Computing Zooms in ratio
                int outHeight     = ops.OutHeight;
                int outWidth      = ops.OutWidth;
                int widthPercent  = outWidth / width;
                int heightPercent = outHeight / height;
                int sampleSize    = 1;
                if (widthPercent < heightPercent)
                {
                    sampleSize = widthPercent;
                }
                else
                {
                    sampleSize = heightPercent;
                }
                if (sampleSize <= 0)
                {
                    sampleSize = 1;
                }
                ops.InSampleSize = sampleSize;
                // Read the picture againand set options.inJustDecodeBounds to false.

                bmp = BitmapFactory.DecodeFile(imageName, ops);
                // Use ThumbnailUtils to create a thumbnail.
                // The size of the thumbnail of the access control file on the server cannot exceed 8 times the size of the file.
                // If the large thumbnail of some small images is generated by 1680*1920, the upload fails.
                if (outHeight < height || outWidth < width)
                {
                    bmp = ThumbnailUtils.ExtractThumbnail(bmp, outWidth, outHeight, ThumnailExtractOptions.RecycleInput);
                }
                else
                {
                    bmp = ThumbnailUtils.ExtractThumbnail(bmp, width, height, ThumnailExtractOptions.RecycleInput);
                }

                string       fileNameParent = thumbnailName.Substring(0, thumbnailName.LastIndexOf(Java.IO.File.Separator));
                Java.IO.File file           = new Java.IO.File(fileNameParent);
                if (!file.Exists())
                {
                    bool mkdirs = file.Mkdirs();
                    if (!mkdirs)
                    {
                        Log.Logger.Error(Tag, "getImageThumbnail file.mkdirs fail");
                    }
                }
                os = new FileStream(thumbnailName, FileMode.OpenOrCreate);
                if (type == FileTypePng)
                {
                    bmp.Compress(Bitmap.CompressFormat.Png, 90, os);
                }
                else
                {
                    bmp.Compress(Bitmap.CompressFormat.Jpeg, 90, os);
                }
            }
            catch (Java.IO.FileNotFoundException e)
            {
                Log.Logger.Error(Tag, "read or write file error");
            }
            catch (Exception e)
            {
                Log.Logger.Error(Tag, "internal error " + e.ToString());
            }
            finally
            {
                if (os != null)
                {
                    try
                    {
                        os.Close();
                    }
                    catch (Exception e)
                    {
                        Log.Logger.Error(Tag, "close FileOutputStream error");
                    }
                }
            }
        }
Ejemplo n.º 11
0
        public static Bitmap LoadAndCropBitmap(this string fileName, int targetSize)
        {
            Bitmap theMap = LoadAndResizeBitmap(fileName, targetSize);

            return(ThumbnailUtils.ExtractThumbnail(theMap, targetSize, targetSize));
        }
Ejemplo n.º 12
0
 public override void OnActivityResult(int requestCode, int resultCode, Intent data
                                       )
 {
     base.OnActivityResult(requestCode, resultCode, data);
     if (resultCode != ResultOk)
     {
         if (mCurrentTaskToAttachImage != null)
         {
             mCurrentTaskToAttachImage = null;
         }
         return;
     }
     if (requestCode == RequestTakePhoto)
     {
         mImageToBeAttached = BitmapFactory.DecodeFile(mImagePathToBeAttached);
         // Delete the temporary image file
         FilePath file = new FilePath(mImagePathToBeAttached);
         file.Delete();
         mImagePathToBeAttached = null;
     }
     else
     {
         if (requestCode == RequestChoosePhoto)
         {
             try
             {
                 Uri uri = data.GetData();
                 mImageToBeAttached = MediaStore.Images.Media.GetBitmap(Activity.GetContentResolver
                                                                            (), uri);
             }
             catch (IOException e)
             {
                 Log.E(Application.Tag, "Cannot get a selected photo from the gallery.", e);
             }
         }
     }
     if (mImageToBeAttached != null)
     {
         if (mCurrentTaskToAttachImage != null)
         {
             try
             {
                 Task.AttachImage(mCurrentTaskToAttachImage, mImageToBeAttached);
             }
             catch (CouchbaseLiteException e)
             {
                 Log.E(Application.Tag, "Cannot attach an image to a task.", e);
             }
         }
         else
         {
             // Attach an image for a new task
             Bitmap thumbnail = ThumbnailUtils.ExtractThumbnail(mImageToBeAttached, ThumbnailSizePx
                                                                , ThumbnailSizePx);
             ImageView imageView = (ImageView)Activity.FindViewById(Resource.Id.image);
             imageView.SetImageBitmap(thumbnail);
         }
     }
     // Ensure resetting the task to attach an image
     if (mCurrentTaskToAttachImage != null)
     {
         mCurrentTaskToAttachImage = null;
     }
 }
Ejemplo n.º 13
0
                public override global::Android.Views.View GetView(int position, global::Android.Views.View convertView
                                                                   , ViewGroup parent)
                {
                    if (convertView == null)
                    {
                        LayoutInflater inflater = (LayoutInflater)parent.GetContext().GetSystemService(Context
                                                                                                       .LayoutInflaterService);
                        convertView = inflater.Inflate(Resource.Layout.view_task, null);
                    }
                    Couchbase.Lite.Document task   = (Couchbase.Lite.Document) this.GetItem(position);
                    Bitmap             image       = null;
                    Bitmap             thumbnail   = null;
                    IList <Attachment> attachments = task.GetCurrentRevision().GetAttachments();

                    if (attachments != null && attachments.Count > 0)
                    {
                        Attachment attachment = attachments[0];
                        try
                        {
                            image     = BitmapFactory.DecodeStream(attachment.GetContent());
                            thumbnail = ThumbnailUtils.ExtractThumbnail(image, MainActivity.TasksFragment.ThumbnailSizePx
                                                                        , MainActivity.TasksFragment.ThumbnailSizePx);
                        }
                        catch (Exception e)
                        {
                            Log.E(Application.Tag, "Cannot decode the attached image", e);
                        }
                    }
                    Bitmap    displayImage = image;
                    ImageView imageView    = (ImageView)convertView.FindViewById(Resource.Id.image);

                    if (thumbnail != null)
                    {
                        imageView.SetImageBitmap(thumbnail);
                    }
                    else
                    {
                        imageView.SetImageDrawable(this._enclosing.GetResources().GetDrawable(Resource.Drawable.
                                                                                              ic_camera_light));
                    }
                    imageView.Click += async(sender, e) => {
                        if (displayImage != null)
                        {
                            DispatchImageViewIntent(displayImage);
                        }
                        else
                        {
                            AttachImage(task);
                        }
                    };
                    TextView text = (TextView)convertView.FindViewById(Resource.Id.text);

                    text.SetText((string)task.GetProperty("title"));
                    CheckBox checkBox        = (CheckBox)convertView.FindViewById(Resource.Id.@checked);
                    bool     checkedProperty = (bool)task.GetProperty("checked");
                    bool     @checked        = checkedProperty != null ? checkedProperty : false;

                    checkBox.SetChecked(@checked);
                    checkBox.Click += async(sender, e) => {
                        try
                        {
                            Task.UpdateCheckedStatus(task, checkBox.IsChecked());
                        }
                        catch (CouchbaseLiteException ex)
                        {
                            Log.E(((CouchbaseSample.Android.Application)Application).Tag, "Cannot update checked status", e);
                        }
                    };
                    return(convertView);
                }