Error: The argument type 'List<int>' can't be assigned to the parameter type 'Uint8List' - dart-null-safety

Below is my original codes run well without problem under flutter version 1.22.6, however when I upgraded to flutter version 2.2.1 error of "The argument type 'List' can't be assigned to the parameter type 'Uint8List'." flagged with red error:
final paint = await PaintingBinding.instance!
.instantiateImageCodec(asset != null ? img.encodePng(asset) : buffer);
Anyone could help will be much appreaciated.
This my code:
Future<BeautifulPopup> recolor(Color color) async {
primaryColor = color;
final illustrationData = await rootBundle.load(instance.illustrationKey);
final buffer = illustrationData.buffer.asUint8List();
img.Image asset;
asset = img.readPng(buffer)!;
img.adjustColor(
asset,
saturation: 0,
// hue: 0,
);
img.colorOffset(
asset,
red: primaryColor.red,
// I don't know why the effect is nicer with the number ╮(╯▽╰)╭
green: primaryColor.green ~/ 3,
blue: primaryColor.blue ~/ 2,
alpha: 0,
);
final paint = await PaintingBinding.instance!
.instantiateImageCodec(asset != null ? img.encodePng(asset) : buffer);
final nextFrame = await paint.getNextFrame();
_illustration = nextFrame.image;
return this;
}
...

This is because they are different types. But here is an easy way to handle the conversion:
Uint8List uint8List;
List<int> list;
// convert List<int> to Uint8List.
uint8List = Uint8List.fromList(list);
// convert Uint8List to List<int>
list = List<int>.from(uint8List);
Cheers!
David

Related

Glance fails to load images using the coil

I did this in Glance to get a bitmap of the online URI for display, but it failed.
Does Glance still support weight ratios?
val context = LocalContext.current val imageLoader = ImageLoader(context)
var bitmap = currentState<Bitmap>()
imageLoader.enqueue(
ImageRequest.Builder(context)
.data(parcelItem.artUri)
.error(R.drawable.music)
.target(
onSuccess = {
bitmap = it.toBitmap()
},
onError = {
it?.let {
bitmap = it.toBitmap()
}
}
)
.build()
)
Image(
provider = ImageProvider(bitmap),
modifier = GlanceModifier.size(50.dp).cornerRadius(10.dp).padding(8.dp),
contentDescription = ""
)
It is not possible to use the Coil directly, because the Glance component is required, and the ImageProvider(URI) does not support online resolution.
I just need to get the Bitmap before the update and pass it to the Widget

How to put an image overlay over video

I want to put an image overlay over video, but I'm not sure how I can do this. I'm trying to modify example from this repo Azure Media Services v3 .NET Core tutorials
, bascially what I changed here is transform:
private static Transform EnsureTransformForOverlayExists(IAzureMediaServicesClient client, string resourceGroupName, string accountName, string transformNameNew)
{
Console.WriteLine(transformNameNew);
Transform transform = client.Transforms.Get(resourceGroupName, accountName, transformName);
if (transform == null)
{
TransformOutput[] outputs = new TransformOutput[]
{
new TransformOutput(
new StandardEncoderPreset(
codecs: new Codec[]
{
new AacAudio(
channels: 2,
samplingRate: 48000,
bitrate: 128000,
profile: AacAudioProfile.AacLc
),
new H264Video(stretchMode: "AutoFit",
keyFrameInterval: TimeSpan.FromSeconds(2),
layers: new[]
{
new H264Layer(
bitrate: 1500000,
maxBitrate: 1500000,
width: "640",
height: "360"
)
}
),
new PngImage(
start: "25%",
step: "25%",
range: "80%",
layers: new PngLayer[]{
new PngLayer(
width: "50%",
height: "50%"
)
}
),
},
filters: new Filters
{
Overlays = new List<Overlay>
{
new VideoOverlay("input1")
}
},
formats: new Format[]
{
new Mp4Format(
filenamePattern: "{Basename}_letterbox{Extension}"
),
new PngFormat(
filenamePattern: "{Basename}_{Index}_{Label}_{Extension}"
),
}
))
};
transform = client.Transforms.CreateOrUpdate(resourceGroupName, accountName, transformName, outputs);
}
return transform;
}
and RunAsync method to provide multiple inputs where one of them should be an overlay:
private static async Task RunAsync(ConfigWrapper config)
{
IAzureMediaServicesClient client = await CreateMediaServicesClientAsync(config);
// Set the polling interval for long running operations to 2 seconds.
// The default value is 30 seconds for the .NET client SDK
client.LongRunningOperationRetryTimeout = 2;
try
{
// Ensure that you have customized encoding Transform. This is really a one time setup operation.
Transform overlayTransform = EnsureTransformForOverlayExists(client, config.ResourceGroup, config.AccountName, transformName);
// Creating a unique suffix so that we don't have name collisions if you run the sample
// multiple times without cleaning up.
string uniqueness = Guid.NewGuid().ToString().Substring(0, 13);
string jobName = "job-" + uniqueness;
string inputAssetName = "input-" + uniqueness;
string outputAssetName = "output-" + uniqueness;
Asset asset = client.Assets.CreateOrUpdate(config.ResourceGroup, config.AccountName, inputAssetName, new Asset());
var inputs = new JobInputs(new List<JobInput>());
var input = new JobInputHttp(
baseUri: "https://nimbuscdn-nimbuspm.streaming.mediaservices.windows.net/2b533311-b215-4409-80af-529c3e853622/",
files: new List<String> {"Ignite-short.mp4"},
label:"input1"
);
inputs.Inputs.Add((input));
input = new JobInputHttp(
baseUri: "SomeBaseUriHere",
files: new List<string> {"AssetVideo_000001_None_.png"},
label: "overlay");
inputs.Inputs.Add((input));
Asset outputAsset = CreateOutputAsset(client, config.ResourceGroup, config.AccountName, outputAssetName);
Job job = SubmitJob(client, config.ResourceGroup, config.AccountName, transformName, jobName, inputs, outputAsset.Name);
DateTime startedTime = DateTime.Now;
job = WaitForJobToFinish(client, config.ResourceGroup, config.AccountName, transformName, jobName);
TimeSpan elapsed = DateTime.Now - startedTime;
if (job.State == JobState.Finished)
{
Console.WriteLine("Job finished.");
if (!Directory.Exists(outputFolder))
Directory.CreateDirectory(outputFolder);
await MakeContainerPublic(client, config.ResourceGroup, config.AccountName, outputAsset.Name, config.BlobConnectionString);
DownloadResults(client, config.ResourceGroup, config.AccountName, outputAsset.Name, outputFolder).Wait();
}
else if (job.State == JobState.Error)
{
Console.WriteLine($"ERROR: Job finished with error message: {job.Outputs[0].Error.Message}");
Console.WriteLine($"ERROR: error details: {job.Outputs[0].Error.Details[0].Message}");
}
}
catch(ApiErrorException ex)
{
string code = ex.Body.Error.Code;
string message = ex.Body.Error.Message;
Console.WriteLine("ERROR:API call failed with error code: {0} and message: {1}", code, message);
}
}
But I have this error
Microsoft.Cloud.Media.Encoding.PresetException: Preset ERROR: There are 2 input assets. Preset has 2 Source but does NOT specify AssetID for each Source
and I have no idea how to overcome this.
At this time, it is not possible to use v3 APIs to create overlays. The feature is not fully implemented. See this link for other gaps between the v2 and v3 APIs.
For more details, you can see this site .

Spring Cloud Open Feign: Decoder for ByteArrayResource

I have a Spring Boot Rest End Point defined in an interface to download an image
#GetMapping(value = "/{name}")
ResponseEntity<ByteArrayResource> getFileByName(#PathVariable("name") String name);
And I use Feign Builder to invoke this end point.
Feign.builder()
.client(new ApacheHttpClient())
.contract(new SpringMvcContract())
.decoder(new JacksonDecoder())
.encoder(new JacksonEncoder())
.target(clazz, url)
On invoking, I get below error
com.fasterxml.jackson.core.JsonParseException: Unexpected character ('�' (code 65533 / 0xfffd)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
at [Source: (BufferedReader); line: 1, column: 2]
When I try to invoke the end point directly from Insomnia, it works fine. But fails through Feign Builder. The response content type is image/jpeg
Is there any specific decoder in feign to handle ByteArrayResource? I tried ResponseEntityDecoder, StreamDecoder and JacksonDecoder. None of it works.
On debugging, I see that Jackson ObjectMapper readValue fails. I tried changing the return type from ByteArraySource to byte[], didn't work either.
Any help?
I wrote my own little decoder and the problem was resolved. Below is the decoder
private Decoder byteArrayResourceDecoder() {
Decoder decoder = (response, type) -> {
if (type instanceof Class && ByteArrayResource.class.isAssignableFrom((Class) type)) {
return StreamUtils.copyToByteArray(response.body().asInputStream());
}
return new JacksonDecoder().decode(response, type);
};
return new ResponseEntityDecoder(decoder);
}
Hope this template helps others who has similar issues. Would have expected Feign to have decoder that supports all return types.
Thanks Maz - your solution helped me.
I modified your solution for my needs to read Spring StreamingResponseBody
1.) Create the decoder wrapper that either returns JacksonDecoder (Default) or reads the responsebody into a byte array.
Decoder decoder = (response, type) -> {
Map<String, Collection<String>> headers = response.headers();
Collection<String> contentType = null;
for (String x : headers.keySet()){
if ("content-type".equals(x.toLowerCase())){
contentType = headers.get(x);
}
}
if (contentType == null || contentType.stream().filter(x -> x.contains("application/json")).findFirst().isPresent()) {
return new JacksonDecoder(getMapper()).decode(response, type);
}
InputStream initialStream = response.body().asInputStream();
byte[] buffer = new byte[512];
byte[] result = null;
try(ByteArrayOutputStream out = new ByteArrayOutputStream()) {
try {
int length = 0;
while ((length = initialStream.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
} finally {
out.flush();
}
result = out.toByteArray();
} finally {
initialStream.close();
}
return result;
};
2.) Use the custom decoder with the Feign.Builder
Feign.Builder builder = Feign.builder()
// --
.decoder(decoder)
// --
openfeignfeignspringstreamingresponsebody

.NET WPF. OxyPlot TimeFormat

I need to display time in format "HH:mm:ss" in the window.
Plot = new PlotModel();
Plot.TextColor = OxyColors.Black;
Plot.Axes.Add(new LinearAxis(AxisPosition.Left, 0, 100));
Plot.Axes.Add(new DateTimeAxis(AxisPosition.Bottom)
{
//StringFormat = "h:mm",
IsZoomEnabled = false,
IntervalType = DateTimeIntervalType.Seconds,
IntervalLength = 80
});
But it doesn't work.
I want to see this result in DateTimeAxis: 0:00:01 - 0:00:05 - 0:00:10 etc.
Help me, please.
https://github.com/oxyplot
private double _xAxisCounter;
private void UpdateChart(int mixerNumber)
{
DetailsPlot details = _mixerDetailsPlots[mixerNumber];
UpdateChart(details.LineOfCurrent, details.Mixer.Current.Value);
UpdateChart(details.LineOfMaximumCurrent, details.Mixer.MaximumCurrent);
}
private void UpdateChart(LineSeries line, double value)
{
if (line.Points.Count > 500)
{
line.Points.RemoveAt(0);
}
line.Points.Add(new DataPoint(_xAxisCounter, value));
}
I'm pretty sure you're after something like this:
var BottomAxis = new DateTimeAxis();
BottomAxis.MajorGridlineStyle = LineStyle.Solid;
BottomAxis.MinorGridlineStyle = LineStyle.Dot;
BottomAxis.LabelFormatter = d => { return DateTimeAxis.ToDateTime(d).ToString("HH:mm:ss\nyy/MM/dd"); };
myPlotModel.Axes.Add(BottomAxis);
All I've done is added a format to the DateTime axis.
In your case you won't need the date part of the format.
Hope this helps!

windows phone create database with items

I am building a simple application for windows phone. I want to create a database and want to have several (lets say 10) items in the database. I am a beginner and every tutorial that i have seen is sth about adding items in the database on button "add" or sth like that. I don't need that, because I want to have several item that are in the database, ready for the user to use them. How can I achieve this? Please write to me in a clear way, because I am still a beginner. If you can provide some links of examples or tutorials, that would be great. Thank u!
If you need to have the preloaded DB then you can Add a sqlCe DB in your application and populate the db with your seed Data.
then you can copy the DB file to your ISO Store while your Constructor of DBContext is invoked.
public Moviadb1DataContext (string connectionString) : base(connectionString)
{
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
if (!iso.FileExists("Moviadb1.sdf"))
{
MoveReferenceDatabase();
}
if (!DatabaseExists())
CreateDatabase();
}
public static void MoveReferenceDatabase()
{
// Obtain the virtual store for the application.
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
// Create a stream for the file in the installation folder.
using (Stream input = Application.GetResourceStream(new Uri("Moviadb1.sdf", UriKind.Relative)).Stream)
{
// Create a stream for the new file in isolated storage.
using (IsolatedStorageFileStream output = iso.CreateFile("Moviadb1.sdf"))
{
// Initialize the buffer.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the file from the installation folder to isolated storage.
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
}
}
}
you can also add some seed data instead of moving the reference DB if you have very small amount of Data.
public ListenDataDataContext (string connectionString) : base(connectionString)
{
if (!DatabaseExists())
{
CreateDatabase();
List<Audiables> PreLoads = new List<Audiables>();
PreLoads.Add(new Audiables { Category = 1, Name = "I want To Eat", AudioLocation = "Sounds/Food/1_IwantToEat.wma", ImageLocation = "Images/Food/1_IwantToEat.jpg" });
PreLoads.Add(new Audiables { Category = 1, Name = "I want To Drink", AudioLocation = "Sounds/Food/1_IwantToDrink.wma", ImageLocation = "Images/Food/1_IwantToDrink.jpg" });
PreLoads.Add(new Audiables { Category = 2, Name = "I want A Ticket", AudioLocation = "Sounds/Travel/1_IwantATicket.wma", ImageLocation = "Images/Travel/1_IwantATicket.jpg" });
PreLoads.Add(new Audiables { Category = 2, Name = "I want To Sit", AudioLocation = "Sounds/Travel/1_IwantToSit.wma", ImageLocation = "Images/Travel/1_IwantToSit.jpg" });
PreLoads.Add(new Audiables { Category = 3, Name = "How Much Is That", AudioLocation = "Sounds/Shopping/1_HowMuchIsThat.wma", ImageLocation = "Images/Shopping/1_HowMuchIsThat.jpg" });
PreLoads.Add(new Audiables { Category = 3, Name = "Please Take the Money", AudioLocation = "Sounds/Shopping/1_PleaseTakeTheMoney.wma", ImageLocation = "Images/Shopping/1_PleaseTakeTheMoney.jpg" });
Audiables.InsertAllOnSubmit(PreLoads);
this.SubmitChanges();
}
}
Happy app making :)
Best way is to check the "Local Database Sample" in the Windows Phone Code Samples!

Resources