찾다
백엔드 개발PHP 튜토리얼PHP에서 code128 바코드를 생성하는 방법에 대한 샘플 코드 공유

이 글은 주로 PHP에서 code128 바코드를 생성하는 방법을 소개합니다. PHP 바코드 생성 클래스의 정의와 사용법을 완전한 예제 형식으로 제공합니다. 필요한 친구는 이를 참조할 수 있습니다.

이 글의 예는 방법을 알려줍니다. PHP 방식으로 code128 바코드를 생성합니다. 참조용으로 모든 사람과 공유하세요. 세부 사항은 다음과 같습니다.

렌더링:


<?php
class BarCode128 {
  const STARTA = 103;
  const STARTB = 104;
  const STARTC = 105;
  const STOP = 106;
  private $unit_width = 1; //单位宽度 缺省1个象素
  private $is_set_height = false;
  private $width = -1;
  private $heith = 35;
  private $quiet_zone = 6;
  private $font_height = 15;
  private $font_type = 4;
  private $color =0x000000;
  private $bgcolor =0xFFFFFF;
  private $image = null;
  private $codes = array("212222","222122","222221","121223","121322","131222","122213","122312","132212","221213","221312","231212","112232","122132","122231","113222","123122","123221","223211","221132","221231","213212","223112","312131","311222","321122","321221","312212","322112","322211","212123","212321","232121","111323","131123","131321","112313","132113","132311","211313","231113","231311","112133","112331","132131","113123","113321","133121","313121","211331","231131","213113","213311","213131","311123","311321","331121","312113","312311","332111","314111","221411","431111","111224","111422","121124","121421","141122","141221","112214","112412","122114","122411","142112","142211","241211","221114","413111","241112","134111","111242","121142","121241","114212","124112","124211","411212","421112","421211","212141","214121","412121","111143","111341","131141","114113","114311","411113","411311","113141","114131","311141","411131","211412","211214","211412","2331112");
  private $valid_code = -1;
  private $type =&#39;B&#39;;
  private $start_codes =array(&#39;A&#39;=>self::STARTA,&#39;B&#39;=>self::STARTB,&#39;C&#39;=>self::STARTC);
  private $code =&#39;&#39;;
  private $bin_code =&#39;&#39;;
  private $text =&#39;&#39;;
  public function __construct($code=&#39;&#39;,$text=&#39;&#39;,$type=&#39;B&#39;)
  {
    if (in_array($type,array(&#39;A&#39;,&#39;B&#39;,&#39;C&#39;)))
      $this->setType($type);
    else
      $this->setType(&#39;B&#39;);
    if ($code !==&#39;&#39;)
      $this->setCode($code);
    if ($text !==&#39;&#39;)
      $this->setText($text);
  }
  public function setUnitWidth($unit_width)
  {
    $this->unit_width = $unit_width;
    $this->quiet_zone = $this->unit_width*6;
    $this->font_height = $this->unit_width*15;
    if (!$this->is_set_height)
    {
      $this->heith = $this->unit_width*35;
    }
  }
  public function setFontType($font_type)
  {
    $this->font_type = $font_type;
  }
  public function setBgcolor($bgcoloe)
  {
    $this->bgcolor = $bgcoloe;
  }
  public function setColor($color)
  {
    $this->color = $color;
  }
  public function setCode($code)
  {
    if ($code !=&#39;&#39;)
    {
      $this->code= $code;
      if ($this->text ===&#39;&#39;)
        $this->text = $code;
    }
  }
  public function setText($text)
  {
    $this->text = $text;
  }
  public function setType($type)
  {
    $this->type = $type;
  }
  public function setHeight($height)
  {
    $this->height = $height;
    $this->is_set_height = true;
  }
  private function getValueFromChar($ch)
  {
    $val = ord($ch);
    try
    {
      if ($this->type ==&#39;A&#39;)
      {
        if ($val > 95)
          throw new Exception(&#39; illegal barcode character &#39;.$ch.&#39; for code128A in &#39;.__FILE__.&#39; on line &#39;.__LINE__);
        if ($val < 32)
          $val += 64;
        else
          $val -=32;
      }
      elseif ($this->type ==&#39;B&#39;)
      {
        if ($val < 32 || $val > 127)
          throw new Exception(&#39; illegal barcode character &#39;.$ch.&#39; for code128B in &#39;.__FILE__.&#39; on line &#39;.__LINE__);
        else
          $val -=32;
      }
      else
      {
        if (!is_numeric($ch) || (int)$ch < 0 || (int)($ch) > 99)
          throw new Exception(&#39; illegal barcode character &#39;.$ch.&#39; for code128C in &#39;.__FILE__.&#39; on line &#39;.__LINE__);
        else
        {
          if (strlen($ch) ==1)
            $ch .=&#39;0&#39;;
          $val = (int)($ch);
        }
      }
    }
    catch(Exception $ex)
    {
      errorlog(&#39;die&#39;,$ex->getMessage());
    }
    return $val;
  }
  private function parseCode()
  {
    $this->type==&#39;C&#39;?$step=2:$step=1;
    $val_sum = $this->start_codes[$this->type];
    $this->width = 35;
    $this->bin_code = $this->codes[$val_sum];
    for($i =0;$i<strlen($this->code);$i+=$step)
    {
      $this->width +=11;
      $ch = substr($this->code,$i,$step);
      $val = $this->getValueFromChar($ch);
      $val_sum += $val;
      $this->bin_code .= $this->codes[$val];
    }
    $this->width *=$this->unit_width;
    $val_sum = $val_sum%103;
    $this->valid_code = $val_sum;
    $this->bin_code .= $this->codes[$this->valid_code];
    $this->bin_code .= $this->codes[self::STOP];
  }
  public function getValidCode()
  {
    if ($this->valid_code == -1)
      $this->parseCode();
    return $this->valid_code;
  }
  public function getWidth()
  {
    if ($this->width ==-1)
      $this->parseCode();
    return $this->width;
  }
  public function getHeight()
  {
    if ($this->width ==-1)
      $this->parseCode();
    return $this->height;
  }
  public function createBarCode($image_type =&#39;png&#39;,$file_name=null)
  {
    $this->parseCode();
    $this->image = ImageCreate($this->width+2*$this->quiet_zone,$this->heith + $this->font_height);
    $this->bgcolor = imagecolorallocate($this->image,$this->bgcolor >> 16,($this->bgcolor >> 8)&0x00FF,$this->bgcolor & 0xFF);
    $this->color = imagecolorallocate($this->image,$this->color >> 16,($this->color >> 8)&0x00FF,$this->color & 0xFF);
    ImageFilledRectangle($this->image, 0, 0, $this->width + 2*$this->quiet_zone,$this->heith + $this->font_height, $this->bgcolor);
    $sx = $this->quiet_zone;
    $sy = $this->font_height -1;
    $fw = 10; //編號為2或3的字體的寬度為10,為4或5的字體寬度為11
    if ($this->font_type >3)
    {
      $sy++;
      $fw=11;
    }
    $ex = 0;
    $ey = $this->heith + $this->font_height - 2;
    for($i=0;$i<strlen($this->bin_code);$i++)
    {
      $ex = $sx + $this->unit_width*(int) $this->bin_code{$i} -1;
      if ($i%2==0)
        ImageFilledRectangle($this->image, $sx, $sy, $ex,$ey, $this->color);
      $sx =$ex + 1;
    }
    $t_num = strlen($this->text);
    $t_x = $this->width/$t_num;
    $t_sx = ($t_x -$fw)/2;    //目的为了使文字居中平均分布
    for($i=0;$i<$t_num;$i++)
    {
      imagechar($this->image,$this->font_type,6*$this->unit_width +$t_sx +$i*$t_x,0,$this->text{$i},$this->color);
    }
    if (!$file_name)
    {
      header("Content-Type: image/".$image_type);
    }
    switch ($image_type)
    {
      case &#39;jpg&#39;:
      case &#39;jpeg&#39;:
        Imagejpeg($this->image,$file_name);
        break;
      case &#39;png&#39;:
        Imagepng($this->image,$file_name);
        break;
      case &#39;gif&#39;:
        break;
        Imagegif($this->image,$file_name);
      default:
        Imagepng($this->image,$file_name);
        break;
    }
  }
}
$barcode = new BarCode128(&#39;88888888&#39;);
$barcode->createBarCode();
?>

첨부된 것은 강력한 바코드 생성 확장 팩입니다:


위 내용은 PHP에서 code128 바코드를 생성하는 방법에 대한 샘플 코드 공유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
세션 고정 공격을 어떻게 방지 할 수 있습니까?세션 고정 공격을 어떻게 방지 할 수 있습니까?Apr 28, 2025 am 12:25 AM

세션 고정 공격을 방지하는 효과적인 방법은 다음과 같습니다. 1. 사용자 로그인 한 후 세션 ID 재생; 2. 보안 세션 ID 생성 알고리즘을 사용하십시오. 3. 세션 시간 초과 메커니즘을 구현하십시오. 4. HTTPS를 사용한 세션 데이터를 암호화합니다. 이러한 조치는 세션 고정 공격에 직면 할 때 응용 프로그램이 파괴 할 수 없도록 할 수 있습니다.

세션리스 인증을 어떻게 구현합니까?세션리스 인증을 어떻게 구현합니까?Apr 28, 2025 am 12:24 AM

서버 측 세션 스토리지가없는 토큰에 저장되는 토큰 기반 인증 시스템 인 JSONWEBTOKENS (JWT)를 사용하여 세션없는 인증 구현을 수행 할 수 있습니다. 1) JWT를 사용하여 토큰을 생성하고 검증하십시오. 2) HTTPS가 토큰이 가로 채지 못하도록하는 데 사용되도록, 3) 클라이언트 측의 토큰을 안전하게 저장, 4) 변조 방지를 방지하기 위해 서버 측의 토큰을 확인하기 위해 단기 접근 메커니즘 및 장기 상쾌한 토큰을 구현하십시오.

PHP 세션과 관련된 일반적인 보안 위험은 무엇입니까?PHP 세션과 관련된 일반적인 보안 위험은 무엇입니까?Apr 28, 2025 am 12:24 AM

PHP 세션의 보안 위험에는 주로 세션 납치, 세션 고정, 세션 예측 및 세션 중독이 포함됩니다. 1. HTTPS를 사용하고 쿠키를 보호하여 세션 납치를 방지 할 수 있습니다. 2. 사용자가 로그인하기 전에 세션 ID를 재생하여 세션 고정을 피할 수 있습니다. 3. 세션 예측은 세션 ID의 무작위성과 예측 불가능 성을 보장해야합니다. 4. 세션 중독 데이터를 확인하고 필터링하여 세션 중독을 방지 할 수 있습니다.

PHP 세션을 어떻게 파괴합니까?PHP 세션을 어떻게 파괴합니까?Apr 28, 2025 am 12:16 AM

PHP 세션을 파괴하려면 먼저 세션을 시작한 다음 데이터를 지우고 세션 파일을 파괴해야합니다. 1. 세션을 시작하려면 세션 _start ()를 사용하십시오. 2. Session_Unset ()을 사용하여 세션 데이터를 지우십시오. 3. 마지막으로 Session_Destroy ()를 사용하여 세션 파일을 파괴하여 데이터 보안 및 리소스 릴리스를 보장하십시오.

PHP의 기본 세션 저장 경로를 어떻게 변경할 수 있습니까?PHP의 기본 세션 저장 경로를 어떻게 변경할 수 있습니까?Apr 28, 2025 am 12:12 AM

PHP의 기본 세션 저장 경로를 변경하는 방법은 무엇입니까? 다음 단계를 통해 달성 할 수 있습니다. session_save_path를 사용하십시오 ( '/var/www/sessions'); session_start (); PHP 스크립트에서 세션 저장 경로를 설정합니다. php.ini 파일에서 세션을 설정하여 세션 저장 경로를 전 세계적으로 변경하려면 세션을 설정하십시오. memcached 또는 redis를 사용하여 ini_set ( 'session.save_handler', 'memcached')과 같은 세션 데이터를 저장합니다. ini_set (

PHP 세션에 저장된 데이터를 어떻게 수정합니까?PHP 세션에 저장된 데이터를 어떻게 수정합니까?Apr 27, 2025 am 12:23 AM

tomodifyDatainAphPessess, startSessionstession_start (), 그런 다음 $ _sessionToset, modify, orremovevariables.

PHP 세션에 배열을 저장하는 예를 제시하십시오.PHP 세션에 배열을 저장하는 예를 제시하십시오.Apr 27, 2025 am 12:20 AM

배열은 PHP 세션에 저장할 수 있습니다. 1. 세션을 시작하고 session_start ()를 사용하십시오. 2. 배열을 만들고 $ _session에 저장하십시오. 3. $ _session을 통해 배열을 검색하십시오. 4. 세션 데이터를 최적화하여 성능을 향상시킵니다.

Garbage Collection은 PHP 세션에 어떻게 효과가 있습니까?Garbage Collection은 PHP 세션에 어떻게 효과가 있습니까?Apr 27, 2025 am 12:19 AM

PHP 세션 쓰레기 수집은 만료 된 세션 데이터를 정리하기위한 확률 메커니즘을 통해 트리거됩니다. 1) 구성 파일에서 트리거 확률 및 세션 수명주기를 설정합니다. 2) CRON 작업을 사용하여 고재 응용 프로그램을 최적화 할 수 있습니다. 3) 데이터 손실을 피하기 위해 쓰레기 수집 빈도 및 성능의 균형을 맞춰야합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구