1

I create app which recognize elements from picture. Now I have image in File class and I want to rotate image about few degrees and again have image in File class. Is there any solution how to resolve this?

P.S I don't want display this image. I must pass image as File object to some method.

Marcin
  • 45
  • 5

1 Answers1

2

To rotate the actual file in memory use the image library and the copyRotate function.

Image copyRotate(Image src, num angle, {
   Interpolation interpolation = Interpolation.nearest
  }
);
//Returns a copy of the [src] image, rotated by [angle] degrees.

Example:

import 'dart:io';
import 'package:image/image.dart';
void main() {
  // Read an image from file (webp in this case).
  // decodeImage will identify the format of the image and use the appropriate
  // decoder.
  Image image = decodeImage(File('test.webp').readAsBytesSync());

  Image thumbnail = copyRotate(image, 120);

  // Save the thumbnail as a PNG.
  File('thumbnail.png').writeAsBytesSync(encodePng(thumbnail));
}

source

To display a rotated version of the image stored, you can use a RotationTransition with an AlwaysStoppedAnimation like-

new RotatedBox(
  quarterTurns: 1,
  child: new Text("Lorem ipsum")
)

or the Transform.rotate() widget like-

  Transform.rotate(angle: - math.pi / 4, child: Text("Text"),);

for your use case-

  Transform.rotate(angle: degrees*3.14/180, child: Image.asset("file_path"),);
cmd_prompter
  • 1,566
  • 10
  • 16
  • I don't want display this image. I want to have rotated image as File object. – Marcin Dec 19 '19 at 18:17
  • Thanks for answer. This solution works but when image from camera has size 4MB, decoding this image takes about 30 sec, and next encoding about 10 sec. This is unacceptable in my app :/ . I think that exist solution which take less time but I can't find anything. – Marcin Dec 21 '19 at 12:50
  • Did it take that long in debug mode or in release mode? – cmd_prompter Dec 21 '19 at 13:36
  • I measured time in release mode :/ – Marcin Dec 21 '19 at 13:55
  • [see this about the processing time](https://stackoverflow.com/questions/55621239/why-flutter-dart-is-so-slow-to-process-image). Mark my answer as accepted if you think my answer helped you . – cmd_prompter Dec 21 '19 at 16:14
  • Is there any way to update the image being shown with the new file stored in memory instead of using Transform or RotatedBox? – Chris Oct 23 '20 at 13:26
  • @Chris please see the first part of my answer. – cmd_prompter Nov 10 '20 at 14:26