snapshot.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2017 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "ui/snapshot/snapshot.h"
  5. #include <utility>
  6. #include "base/bind.h"
  7. #include "base/callback.h"
  8. #include "base/task/thread_pool.h"
  9. #include "third_party/skia/include/core/SkBitmap.h"
  10. #include "ui/gfx/codec/png_codec.h"
  11. #include "ui/gfx/image/image.h"
  12. #include "ui/gfx/image/image_skia.h"
  13. #include "ui/gfx/image/image_skia_rep.h"
  14. #include "ui/gfx/image/image_util.h"
  15. namespace ui {
  16. namespace {
  17. scoped_refptr<base::RefCountedMemory> EncodeImageAsPNG(
  18. const gfx::Image& image) {
  19. if (image.IsEmpty())
  20. return nullptr;
  21. DCHECK(!image.AsImageSkia().GetRepresentation(1.0f).is_null());
  22. return image.As1xPNGBytes();
  23. }
  24. scoped_refptr<base::RefCountedMemory> EncodeImageAsJPEG(
  25. const gfx::Image& image) {
  26. std::vector<uint8_t> result;
  27. DCHECK(!image.AsImageSkia().GetRepresentation(1.0f).is_null());
  28. gfx::JPEG1xEncodedDataFromImage(image, 100, &result);
  29. return base::RefCountedBytes::TakeVector(&result);
  30. }
  31. void EncodeImageAndScheduleCallback(
  32. scoped_refptr<base::RefCountedMemory> (*encode_func)(const gfx::Image&),
  33. base::OnceCallback<void(scoped_refptr<base::RefCountedMemory> data)>
  34. callback,
  35. gfx::Image image) {
  36. base::ThreadPool::PostTaskAndReplyWithResult(
  37. FROM_HERE, {base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
  38. base::BindOnce(encode_func, std::move(image)), std::move(callback));
  39. }
  40. } // namespace
  41. void GrabWindowSnapshotAsyncPNG(gfx::NativeWindow window,
  42. const gfx::Rect& source_rect,
  43. GrabWindowSnapshotAsyncPNGCallback callback) {
  44. GrabWindowSnapshotAsync(
  45. window, source_rect,
  46. base::BindOnce(&EncodeImageAndScheduleCallback, &EncodeImageAsPNG,
  47. std::move(callback)));
  48. }
  49. void GrabWindowSnapshotAsyncJPEG(gfx::NativeWindow window,
  50. const gfx::Rect& source_rect,
  51. GrabWindowSnapshotAsyncJPEGCallback callback) {
  52. GrabWindowSnapshotAsync(
  53. window, source_rect,
  54. base::BindOnce(&EncodeImageAndScheduleCallback, &EncodeImageAsJPEG,
  55. std::move(callback)));
  56. }
  57. } // namespace ui