且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将图像文件流高效地转换为HttpResponse

更新时间:2023-02-16 20:43:19

我想这可能会帮助你 - 我加速了4-5倍:



我将在这里添加完整的例子:

  Future< ServerSocket&gt ; future = ServerSocket.bind(127.0.0.1,1000); 
future.then((ServerSocket sock){
HttpServer s = new HttpServer.listenOn(sock);

s.listen((HttpRequest req){
req .response.statusCode = HttpStatus.OK;
req.response.headers.contentType = ContentType.parse(image / png);
var file = new File(someImage.png);

//平均大约5-7ms
未来f = file.readAsBytes();
req.response.addStream(f.asStream())。
req.response.close();
});
//平均值〜25-30ms
/ *
file.readAsBytes()。 List< int> bytes){
bytes.forEach((int b)=> req.response.writeCharCode(b)); // slow!
req.response.close();
});
* /
});
});这是否解决了您的问题?

致谢
Robert

My server-side Dart web app serves image files for certain requests.

Simplified, here's what it currently does:

   HttpServer.bind(InternetAddress.ANY_IP_V4, 80)
    .then((HttpServer server) {    
      server.listen((HttpRequest request) {      
        request.response.statusCode = HttpStatus.OK;
        request.response.headers.contentType = ContentType.parse("image/jpg");
        var file = new File("C:\\images\\myImage.jpg");
        file.readAsBytes().then((List<int> bytes) {
          bytes.forEach((int b) => request.response.writeCharCode(b)); // slow!
          request.response.close();       
        });    
      }
   }

This works, but it's fairly slow and I suspect that writing every byte individually via HttpResponse.writeCharCode is what's slowing things down here.

Unfortunately, there's no such thing as .writeAllCharCodes on HttpResponse. There's writeAll, but it calls toString() on every element of the byte array - we need to write the raw bytes.

Any suggestions?

I think this might help you - I got a speed up of about 4-5 times:

I will add my complete example here:

Future<ServerSocket> future = ServerSocket.bind("127.0.0.1", 1000);
future.then((ServerSocket sock) {
  HttpServer s = new HttpServer.listenOn(sock);

  s.listen((HttpRequest req) {
    req.response.statusCode = HttpStatus.OK;
    req.response.headers.contentType = ContentType.parse("image/png");
    var file = new File("someImage.png");

    // Average of about 5-7ms
    Future f = file.readAsBytes();
    req.response.addStream(f.asStream()).whenComplete(() {
      req.response.close();
    });
    // Average of ~25-30ms
    /*
    file.readAsBytes().then((List<int> bytes) {
      bytes.forEach((int b) => req.response.writeCharCode(b)); // slow!
      req.response.close();       
    });
    */ 
  });
});

Does this resolve your problem?

Regards Robert