Dart Fails to save Bytes to PNG, JPEG - flutter

I have been trying for hours to figure out why my code is not working. Basically, I have an image. I load its bytes into dart as a list of Uint8List. Then, I replace the values of the list with some other values. The problem is that after replacing the values, when I call the File().writeAsBytes() function, the image is CORRUPTED. Don't know why this is happening. Tried doing everything I could.
var b = File("assets/1K91k (1).jpg").readAsBytesSync();
void main() {
runApp(const MyApp());
for (int i = 0; i < b.length; i++) {
double check = b[i] / 255;
if (check > 0.8) {
b[i] = 255;
} else {
b[i] = 2;
}
}
File("/home/kq1231/Desktop/test.jpg")
..createSync()
..writeAsBytesSync(b);
}
I tried converting the b list to a Uint8List but to no avail.

Feels funny to answer my own question but here's how it got working:
import 'package:image/image.dart' as image;
import 'dart:io';
image.Image prettify(String fileName, String exportPath, String imageName,
double threshold, int blurRadius) {
var b = image.decodeImage(File(fileName).readAsBytesSync());
b = image.gaussianBlur(b!, blurRadius);
for (int i = 0; i < b.width; i++) {
for (int j = 0; j < b.height; j++) {
var pix = b.getPixel(i, j);
if ((image.getBlue(pix) + image.getRed(pix) + image.getGreen(pix)) /
(255 * 3) >
threshold) {
b.setPixel(i, j, 0xffffff);
} else {
b.setPixel(i, j, 0);
}
}
}
File("$exportPath/$imageName")
..createSync()
..writeAsBytesSync(image.encodePng(b));
return b;
}
This is a function called prettify. It applies a specific operation to a given image. First, decode the image. Then, loop through each pixel, average the R, G and B values to get the grayscale value (get the value of the pixel using image.getPixel() and set its value using image.setPixel()). Then, encode it back to .png format and save it.
Note that image is the name of the library imported.

Related

Converting matrix of colors to image in flutter

I need to convert List<List<int>>> to an dart:ui.Image. I have an algorithm to convert an integer to a color. I tried to do this by drawing one-pixel rectangles on the dart:ui.Canvas, but it is about 100 times slower than I expected! _getPixelColor is the method by which I convert int to Color. Here is my code:
Future<void> matrixToImage(FField sourceMatrix) async {
PictureRecorder p = PictureRecorder();
Canvas c = Canvas(
p,
Rect.fromLTWH(0, 0, sourceMatrix.length.toDouble(),
sourceMatrix[0].length.toDouble()));
Paint paint = Paint();
for (int x = 0; x < sourceMatrix.length; x++) {
for (int y = 0; y < sourceMatrix[0].length; y++) {
int pixelValue = sourceMatrix[x][y];
paint.color = _getPixelColor(pixelValue / 40 / paletteLength + paletteOffset);
c.drawRect(Rect.fromLTWH(x.toDouble(), y.toDouble(), 1, 1), paint);
}
}
Picture picture = p.endRecording();
Image result = await picture.toImage(sourceMatrix.length, sourceMatrix[0].length);
}
If you can compute your int value to an int value that the Image class understands, you don't need the detour through canvas drawing.
Just use Image.fromBytes with the .value of the Color as the list of ints.
That depends on how the image data is stored in the list of INTs.
Generally, I like this package to manipulate images and display them:
https://pub.dev/packages/image
import 'package:image/image.dart' as im;
im.Image? img = decodeImage(bytes); // different-IMAGE class !
Uint8List uint8list = getEncodedJpg(img!,quality: 85) as Uint8List;
// ...
build(BuildContext context) {
return Container(child:
Image.memory(uint8list) // material-IMAGE class !
);
}

Dart find the capital word in a given String

How can I write a code that finds capital words in a given string in dart
for example
String name ='deryaKimlonLeo'
//output='KL'
Hmmm try this using pattern if you only want to get only the big letter then try this
String name ='deryaKimlonLeo';
print(name.replaceAll(RegExp(r'[a-z]'),""));
//Output you wanted will be
// KL
try this on dart pad it works
A basic way of doing this is like
void main() {
String name = 'deryaKimlonLeo';
String result = '';
for (int i = 0; i < name.length; i++) {
if (name.codeUnitAt(i) <= 90 && name.codeUnitAt(i) >= 65) {
result += name[i];
}
}
print(result);
}
More about ASCII and codeUnitAt.
sample code:
void main() {
String test = "SDFSDdsfdDFDS";
for (int i = 0; i < test.length; i++) {
if (test[i].compareTo('A') >= 0 && test[i].compareTo('Z') <= 0)
print(test[i]);
}
}

Attempts to call a method in the same class not working (java)

I'm creating a random number generator which then sorts the digits from largest to smallest. Initially it worked but then I changed a few things. As far as I'm aware I undid all the changes (ctrl + z) but now I have errors at the points where i try to call the methods. This is probably a very amateur problem but I haven't found an answer. The error i'm met with is "method in class cannot be applied to given types"
Here's my code:
public class RandomMath {
public static void main(String[] args) {
String bigger = bigger(); /*ERROR HERE*/
System.out.println(bigger);
}
//create method for generating random numbers
public static int generator(int n){
Random randomGen = new Random();
//set max int to 10000 as generator works between 0 and n-1
for(int i=0; i<1; i++){
n = randomGen.nextInt(10000);
// exclude 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999, 0000
if((n==1111 || n==2222 || n==3333 || n ==4444 || n==5555)
||(n==6666 || n==7777 || n==8888 || n==9999 || n==0000)){
i--;
}
}
return n;
}
//create method for denoting the bigger number
public static String bigger(int generated){
generated = generator(); /*ERROR HERE*/
System.out.println(generated);
int[] times = new int[10];
while (generated != 0) {
int val = generated % 10;
times[val]++;
generated /= 10;
}
String bigger = "";
for (int i = 9; i >= 0; i--) {
for (int j = 0; j < times[i]; j++) {
bigger += i;
}
}
return bigger;
}
}
You have not defined a method bigger(), only bigger(int generated). Therefore, you must call your bigger method with an integer parameter.

Why am I getting this dynamic IndexOutOfBounds Exception?

I am trying to write a program where text is translated into hexadecimal, then into decimal, and then into an (R, G, B) format. However, when trying to incorporate ClickableRectangle, I get an ArrayIndexOutOfBounds exception that changes dynamically with the sign of rects.
Any thoughts on my problem/optimization?
char[] colors; //Array of characters to be translated into hexadecimal
String r = ""; //Red value of color
String g = ""; //Green value of color
String b = ""; //Blue value of color
int x = 0; //X-coordinate of rectangle
int y = 0; //Y-coordinate of rectangle
int q; //Character count
ClickableRectangle[] rects = new ClickableRectangle[400*400]; //Rectangles
void settings() {
size(displayWidth, displayHeight);
}
void setup() {
background(0);
colors = new char[3];
String s = ([INSERT TRANSCRIPT HERE]); //Too long to be in post//
for (int i = 0; i < s.length(); i+=3) {
for (int j = i; j < i+3; j++) {
colors[j-i] = s.charAt(j);
}
r = hex(colors[0], 2);
g = hex(colors[1], 2);
b = hex(colors[2], 2);
drawAPoint(r, g, b, i);
println(i);
q++;
}
save("SlachtochtFeuf.png"); //Ignore this, using for testing purposes
println("q = " + q);
println("x = " + x);
println("y = " + y);
}
void draw() {
for (int i = 0; i < rects.length; i++) {
if (rects[i].isClicked()) {
println(rects[i].getValue()); //Prints char representation of color
}
}
}
void drawAPoint(String r2, String g2, String b2, int i) {
noStroke();
fill(unhex(r2), unhex(g2), unhex(b2));
rects[i] = new ClickableRectangle(x, y, r2, g2, b2);
rects[i].display();
if (x >= width) {
x = 0;
y += 6;
} else {
x+=6;
}
}
class ClickableRectangle {
int x = 0;
int y = 0;
String r = "";
String g = "";
String b = "";
public ClickableRectangle(int x, int y, String r, String g, String b) {
this.x = x;
this.y = y;
this.r = r;
this.g = g;
this.b = b;
}
public void display() {
fill(unhex(r), unhex(g), unhex(b));
rect(x, y, 6, 6);
}
public void setRGB(String r, String g, String b) {
this.r = r;
this.g = g;
this.b = b;
}
public String getValue() {
return ""+char(unhex(r))+char(unhex(g))+char(unhex(b));
}
public boolean isClicked() {
return mouseX > x && mouseY > y && mouseX < x+6 && mouseY < y+6;
}
}
For future reference, you should tell us exactly which line throws the exception, and you should include all of the code needed to repeat the problem. If the text is too long to post, then narrow it down to a smaller MCVE.
But judging from what I can see, the problem appears to be here:
String s = "test";
for (int i = 0; i < s.length(); i+=3) {
for (int j = i; j < i+3; j++) {
colors[j-i] = s.charAt(j);
}
//other stuff
}
Just run through this in your head:
When i=0 and j=0, you access charAt 0.
When i=0 and j=1, you access charAt 1.
When i=0 and j=2, you access charAt 2.
When i=3 and j=3, you access charAt 3.
When i=3 and j=4, you access charAt 4.
You could also use println() statements to better see what's going on:
for (int i = 0; i < s.length(); i+=3) {
println("i: " + i);
for (int j = i; j < i+3; j++) {
println("j: " + j);
colors[j-i] = s.charAt(j);
}
//other stuff
}
That prints out:
i: 0
j: 0
j: 1
j: 2
0
i: 3
j: 3
j: 4
That last part is the problem- the String I'm using is "test", so it only has 4 characters: charAt(0), charAt(1), charAt(2), and charAt(3). So when you try to access charAt(4), it throws a StringIndexOutOfBoundsException!
I don't know exactly what you're trying to do here, but you'll have to rework your code so that it doesn't try to access characters outside the bounds of the String.
As a side note: it looks like you're trying to code your whole project all at once. Don't do that. Instead, develop this in small increments- try to get smaller pieces working by themselves before you combine them into your whole project. Can you write a separate sketch that simply loops over a String and prints out the characters you're trying to extract? Then if you get stuck, you can use that smaller sketch as your MCVE, and it'll be easier for us to help you.

QRCode encoding and decoding problem

I want to split a file ( a docx file) and use the individual fragments of the file to encode a QRCode such that when the qrcodes are read in sequence, it reproduces the original file.
I was able to split the file and create a bunch of QRCodes but when attempted to recreate the file, the Decoder throws the following Error Message.
"Invalid number of finder pattern detected"
I am using http://www.codeproject.com/KB/cs/qrcode.aspx library.
My encoder code
private List Encode(String content, Encoding encoding, int
System.Drawing.Color qrCodeBackgroundColor,
QRCodeCapacity,System.Drawing.Color qrCodeBackgroundColor,System.Drawing.Color
qrCodeForegroundColor,int qrCodeScale, int NoOfQRcodes)
{
List<Bitmap> _qrcodesImages = new List<Bitmap>();
byte[] _filebytearray = encoding.GetBytes(content);
for (int k = 0,l=0; k < NoOfQRcodes; k++)
{
byte[] _tempByteArray = _filebytearray.Skip(l).Take(QRCodeCapacity).ToArray();
bool[][] matrix = calQrcode(_tempByteArray);
SolidBrush brush = new SolidBrush(qrCodeBackgroundColor);
Bitmap image = new Bitmap((matrix.Length * qrCodeScale) + 1, (matrix.Length * qrCodeScale) + 1);
Graphics g = Graphics.FromImage(image);
g.FillRectangle(brush, new Rectangle(0, 0, image.Width, image.Height));
brush.Color = qrCodeForegroundColor;
for (int i = 0; i < matrix.Length; i++)
{
for (int j = 0; j < matrix.Length; j++)
{
if (matrix[j][i])
{
g.FillRectangle(brush, j * qrCodeScale, i * qrCodeScale, qrCodeScale, qrCodeScale);
}
}
}
_qrcodesImages.Add(image);
l += QRCodeCapacity;
}
return _qrcodesImages;
}