JPEG Camer 图片上传

/* Linksprite */

#include <SoftwareSerial.h>
#include <Ethernet.h>
#include <SPI.h>
#define ReadLen 0x30

byte mac[] = { 0xDE, 0xAC, 0xEA, 0xEF, 0xFF, 0xE2 };
// if you don‘t want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "192.168.9.6";    // name address for Google (using DNS)
char HexTable[] = "0123456789ABCDEF";
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,16,121);
IPAddress gateway(192,168,1,1);
IPAddress dns_server(60,191,134,196);
IPAddress subnet(255,255,0,0);
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

byte incomingbyte;
SoftwareSerial mySerial(4,5);                     //Configure pin 4 and 5 as soft serial port
int a=0x0000,j=0,k=0,count=0;                    //Read Starting address
uint8_t MH,ML;
boolean EndFlag=0;
int errCount=0;
int led=8;

void SendResetCmd();
void SendTakePhotoCmd();
void SendReadDataCmd();
void StopTakePhotoCmd();
void httpRequest(byte bytes[]);

void setup()
{
  Serial.begin(9600);
  mySerial.begin(38400);

  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    Ethernet.begin(mac, ip,dns_server,gateway,subnet);
  }

  setImgSize();
  delay(1000);
  readEcho(false);
  Serial.println("Ready");
}

void loop()
{

     SendResetCmd();
     delay(2000);//After reset, wait 2-3 second to send take picture command
     EndFlag=0;
     a=0x0000;j=0;k=0; count=0;
     MH=0;ML=0;
     SendTakePhotoCmd();
     readEcho(false);
      byte a[ReadLen];
      while(!EndFlag)
      {
         j=0;
         k=0;
         count=0;
         SendReadDataCmd();
         delay(25);

          while(mySerial.available()>0)
          {
               incomingbyte=mySerial.read();
               k++;
               if((k>5)&&(j<ReadLen)&&(!EndFlag))
               {
                 a[j]=incomingbyte;
                 if((a[j-1]==0xFF)&&(a[j]==0xD9)){      //Check if the picture is over
                  EndFlag=1;
                  StopTakePhotoCmd();
                  readEcho(false);
                 }
                 j++;
             count++;
               }
          }
//         for(j=0;j<count;j++)
//         {   if(a[j]<10)
//             Serial.print("00");
//             if(a[j]>=10 && a[j]<100)
//              Serial.print("0");
//             Serial.print(a[j]);
//             Serial.print(" ");
//         }                                       //Send jpeg picture over the serial port
//        Serial.println();

          while(!client.connected()){
             byte aa[]={0,0,0};
             httpRequest(aa,3);
          }
          httpRequest(a,count);
//          for(j=0;j<count;j++)
//          {   if(a[j]<0x10)
//              Serial.print("0");
//              Serial.print(a[j],HEX);
//              Serial.print(" ");
//          }                                       //Send jpeg picture over the serial port
//          Serial.println();
      }
    // delay(30000);
}

//==============byte to hex string===============
 String toHex(byte bs[],int count){
  String bundle="";
   for(int i=0;i<count;i++){
     bundle += (String)( HexTable[ bs[i] / 16]) + (String)( HexTable[bs[i] % 16]);

   }
   return bundle;
}
//==============End byte to hex string=============

//================Http Request Code========================
void httpRequest(byte bytes[],int count){
    // if you get a connection, report back via serial:

  if(!client.connected()){
     Serial.println("disconnecting.");
     client.stop();
     if (client.connect(server, 7896)) {
        Serial.println("connected");
     }else{
     // kf you didn‘t get a connection to the server:
        Serial.println("connection failed");
        errCount++;
        if(errCount>=3){
          digitalWrite(led,HIGH);
          delay(1000);
        }
    }
  } else{

    String bundle=toHex(bytes,count);
    //Serial.println(bundle);
    client.println("GET /main.ashx?m=img&mil=" + String(millis()) + "&b="+ bundle  +" HTTP/1.1");
    client.println("Host:192.168.9.6");
    //client.println("Connection: close");

    client.println();
    delay(10);
    String reply="";
    // if there are incoming bytes available
    // from the server, read them and print them:
    while (client.available()) {
      char c = client.read();
      reply+=c;

    }

    //Serial.println(reply);
    if(reply.indexOf("\"Model\":\"OPEN\"")>=0){
      Serial.println("OPEN");

    }
    if(reply.indexOf("\"Model\":\"CLOSE\"")>=0){
      Serial.println("CLOSE");

    }
    errCount=0;

    //wdt_reset();
  }

}
//================End Http Request Code===============

void readEcho(bool show){
 while(mySerial.available()>0){
   char c=mySerial.read();
   if(show){
   Serial.print(c);
   }
 }
}
//160 * 120
void setImgSize(){
  mySerial.write(0x56);
  mySerial.write((byte)0x00);
  mySerial.write(0x31);
  mySerial.write(0x05);
  mySerial.write(0x04);
  mySerial.write(0x01);
  mySerial.write((byte)0x00);
  mySerial.write(0x19);
  mySerial.write(0x22);

}
//Send Reset command
void SendResetCmd()
{
      mySerial.write(0x56);
      mySerial.write((byte)0x00);
      mySerial.write(0x26);
      mySerial.write((byte)0x00);
}

//Send take picture command
void SendTakePhotoCmd()
{
      mySerial.write(0x56);
      mySerial.write((byte)0x00);
      mySerial.write(0x36);
      mySerial.write(0x01);
      mySerial.write((byte)0x00);
}

//Read data
void SendReadDataCmd()
{
      MH=a/0x100;
      ML=a%0x100;
      mySerial.write(0x56);
      mySerial.write((byte)0x00);
      mySerial.write(0x32);
      mySerial.write(0x0c);
      mySerial.write((byte)0x00);
      mySerial.write(0x0a);
      mySerial.write((byte)0x00);
      mySerial.write((byte)0x00);
      mySerial.write(MH);
      mySerial.write(ML);
      mySerial.write((byte)0x00);
      mySerial.write((byte)0x00);
      mySerial.write((byte)0x00);
      mySerial.write(ReadLen);
      mySerial.write((byte)0x00);
      mySerial.write(0x0a);
      a+=ReadLen;                            //address increases 32,set according to buffer size
}

void StopTakePhotoCmd()
{
      mySerial.write(0x56);
      mySerial.write((byte)0x00);
      mySerial.write(0x36);
      mySerial.write(0x01);
      mySerial.write(0x03);
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Threading;
namespace ColorRecognition.JPEGCamera
{
    public class JPEGCameraRecord
    {
        private  static long GRecId = 0;

        private static int C_MAXLen = 100;
        private static int C_ShrinkageLen = 60;
        private List<byte> Bytes { get; set; } //正在收集的图片(单张)
        private Queue<byte[]> Queue { get; set; } //已经收集的图片集合
        private DateTime? BTime { get; set; }
        private DateTime? ETime { get; set; }
        public Queue<int> SpeedQueue = new Queue<int>();
        public string IP { get; set; }
        public long? LastClientMillis { get; set; }
        public DateTime? LastEditTime { get; set; }
        public long RecId { get; set; }
        /// <summary>
        /// 上传一张要多少秒
        /// </summary>
        public int? Speed { get; set; }

        public void ConcatImg(byte[] bytes)
        {
            lock (this)
            {
                #region
                if (bytes.Length >= 2)
                {
                    if (bytes[0] == 0xFF && bytes[1] == 0xD8)
                    {

                        //开始
                        Bytes.Clear();
                        Bytes = new List<byte>();
                        Bytes.AddRange(bytes);
                        BTime = DateTime.Now;
                    }
                    else if (bytes[bytes.Length - 2] == 0xFF && bytes[bytes.Length - 1] == 0xD9)
                    {
                        //结束
                        Bytes.AddRange(bytes);
                        Queue.Enqueue(Bytes.ToArray());
                        Bytes.Clear();
                        Bytes = new List<byte>();
                        if (Queue.Count >= C_MAXLen)
                        {
                            byte[] r = null;
                            while (Queue.Count > C_ShrinkageLen)
                            {
                                Queue.Dequeue();
                            }
                        }
                        ETime = DateTime.Now;
                        var due =(int)((TimeSpan) (ETime - BTime)).TotalSeconds;
                        SpeedQueue.Enqueue(due);
                        if (SpeedQueue.Count >=5)
                        {
                            SpeedQueue.Dequeue();
                        }
                        Speed=(int) SpeedQueue.Average();
                    }
                    else
                    {
                        if (Bytes.Count > 0)
                        {
                            Bytes.AddRange(bytes);
                        }
                        if (Bytes.Count > 1024 * 1024 * 10) //丢弃超过10M的图片
                        {
                            Bytes.Clear();
                            Bytes = new List<byte>();
                        }
                    }

                }
                #endregion
            }
        }
        public List<byte[]> GetImages()
        {
            lock (this)
            {
                var list = new List<byte[]>();
                foreach (var img in Queue)
                {
                    list.Add(img);
                }
                return list;
            }
        }
        public JPEGCameraRecord()
        {
            Bytes = new List<byte>();
            Queue = new Queue<byte[]>();
            Interlocked.Increment(ref GRecId);
            RecId = GRecId;
        }
        public long? BufferLen
        {
            get
            {
                lock (this)
                {
                    return Bytes.Count;
                }
            }
        }
        public long? ImageCount
        {
            get
            {
                lock (this)
                {
                    return Queue.Count;
                }
            }
        }

    }
    public class JPEGCameraRecordMgr
    {
        private static int C_MAXLen = 200;
        private static int C_ShrinkageLen = 120;
        public readonly static ConcurrentQueue<JPEGCameraRecord> Queue = new ConcurrentQueue<JPEGCameraRecord>();
        public static void Add(byte[] bytes, string ip, long? clientMillis)
        {
            var it = Queue.FirstOrDefault(ent => string.Compare(ent.IP , ip,true)==0);
            if (it == null)
            {
                var record = new JPEGCameraRecord();
                record.IP = ip;
                Queue.Enqueue(record);

                if (Queue.Count > C_MAXLen)
                {
                    JPEGCameraRecord r=null;
                    while (Queue.Count >= C_ShrinkageLen)
                    {
                        Queue.TryDequeue(out r);
                    }
                }
                it = record;
            }
            it.LastClientMillis = clientMillis;
            it.LastEditTime = DateTime.Now;
            it.ConcatImg(bytes);
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace ColorRecognition.JPEGCamera
{
    public class CameraHttpHandle:IHttpHandler
    {
        public HttpRequest Request { get; set; }
        public HttpResponse Response { get; set; }
        public void ProcessRequest(HttpContext context)
        {

            Request = context.Request;
            Response = context.Response;

            Response.ContentType = "text/plain";
            Response.Expires = -1;

            var response = new ResponseBase<String>() { Code = 1 };
            try
            {
                var method = Request["m"];
                if (string.Compare(method, "img", true) == 0)
                {
                    DoCollect();
                }
                else
                {
                    throw new Exception("未知道的方法");
                }

                response.Code = 0;
                response.Msg = "OK";

            }
            catch (Exception ex)
            {
                response.Code = -1;
                response.Msg = ex.Message;

            }

            Response.Write(this.ToJson(response));

        }
        public virtual void  DoCollect()
        {
            long? millis = this.TryParser<long?>(Request["mil"], 0);
            var imgSegment = Request["b"];
            var ip = this.GetClientIP();
            if (!string.IsNullOrWhiteSpace(imgSegment))
            {
                var bytes=new byte[imgSegment.Length/2];
                int j = 0;
                for(int i=0;i<imgSegment.Length;i+=2){
                    var v = imgSegment.Substring(i, 2);
                    bytes[j] = byte.Parse(v,System.Globalization.NumberStyles.HexNumber);
                    j++;
                }
                JPEGCameraRecordMgr.Add(bytes, ip, millis);
            }
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }
}

时间: 2024-10-01 00:28:46

JPEG Camer 图片上传的相关文章

jq upload图片上传代码

/* * 图片上传 * */ function postImgData() { $("#addFileInfo input[name='file']").change(function () { console.log($(this).val()) if (!$(this).val()) { return } var fileTyle = $(this).val().split("."); console.log(fileTyle); if (fileTyle[1]

微信端调取相册和摄像头,实现图片上传,并上传到本地服务器

在微信公众号网页开发时,遇到了图片上传的问题,查看了微信的开发者文档,里面的资料比较全.接着我们看一下整个的流程 1.config权限配置 $.ajax({ url:'wx_getConfig', type:'get', dataType:'json', async:false, success:function(data){ var appId = data[0].appId; var timestamp = data[0].timestamp; var nonceStr = data[0].

夺命雷公狗---Thinkphp----12之文章的增删改查(图片上传和关联查询)

我们由于表分析的不够完善,所以我们来加多一个tid的字段,到时候主要目的是为了更好的遍历出文章是属于那个分类下的,表如下所示: 那么下一步我们就开始创建一个ArticleController.class.php的控制器,用来管理文章的增删改查操作,所以我们开始第一步来实现文章的添加,我们先来实现他的增加功能: public function add(){ if(IS_POST){ $data['title'] = I('title'); $data['tid'] = I('tid'); $dat

CKEditor图片上传实现详细步骤(使用Struts 2)

本人使用的CKEditor版本是3.6.3.CKEditor配置和部署我就不多说. CKEditor的编辑器工具栏中有一项"图片域",该工具可以贴上图片地址来在文本编辑器中加入图片,但是没有图片上传. "预览"中有一大堆鸟语,看得很不爽.可以打开ckeditor/plugins/image/dialogs/image.js文件,搜索"b.config.image_previewText"就能找到这段鸟语了,(b.config.image_prev

移动端图片上传解决方案localResizeIMG先压缩后ajax无刷新上传

现在科技太发达,移动设备像素越来越高,随便一张照片2M+,但是要做移动端图片上传和pc上略有不同,移动端你不能去限制图片大小,让用户先处理图片再上传,这样不现实.所以理解的解决方案就是在上传先进行图片压缩,然后再把压缩后的图片上传到服务器. 一翻google之后,发现了localResizeIMG,它会对图片进行压缩成你指定宽度及质量度并转换成base64图片格式,那么我们就可以把这个base64通过ajax传到后台,再进行保存,先压缩后上传的目的就达到了. 处理过程 LocalResizeIM

[原创]超强C#图片上传,加水印,自动生成缩略图源代码

<%@ Page Language=“C#“ AutoEventWireup=“true“ %> <%@ Import Namespace=“System“ %> <%@ Import Namespace=“System.IO“ %> <%@ Import Namespace=“System.Net“ %> <%@ Import NameSpace=“System.Web“ %> <%@ Import NameSpace=“Legalsof

kindeditor图片上传 struts2实现

一.kindeditor以及struts2部署搭建不再赘述,如需要请参考kindeditor使用方法 Struts2框架搭建 二.kindeditor图片上传所依赖jar包在kindeditor\jsp\lib下有 三.以下列出部分核心代码,如需要全部源码可点击下载(待上传) JSP <textarea id="editor_id" name="content" style="width:950px;height:300px;"> 这

项目整合ckeditor实现图片上传到远程服务器

最近手头上的一个Java项目需要做一个门户网站,其中有一个模块就是用来发布最新的业界安全动态的模块,因此需要用到后台发布新闻的功能:刚开始的时候在网上搜了一下,大部分都是关于PHP和.NET的,关于Java不多,而且查到的都是说用ckeditor+ckfinder来实现,ckeditor实现文本的编辑,ckfinder实现图片的上传,刚开始我也是准备用ckeditor+ckfinder来实现的,但是后来研究ckfinder的时候不知道如何配置ckfinder的图片上传路径问题,网上可以找到好多例

kindeditor更改图片上传时网络图片的路径

当我们想要使用kindeditor的图片上传功能时,有两种选择图片方式,一种是本地选择,一种是在图片空间中选择,图片空间的默认地址是服务器上的/kindeditor/attached/image/下面. 如果想要改变这个路径,需要找到/kindeditor/php/file_manager_json.php这个文件,然后可以看到下面几行: //根目录路径,可以指定绝对路径,比如 /var/www/attached/ $root_path = $php_path . '../attached/';