search
HomeBackend DevelopmentPHP Tutorialphp可以去除jpg格式图片的背景并加水印吗?

从网上找到了这段,但我运行并不能实现,而且这个是针对png和gif格式的
$fnew = "a.png";
$img = file_get_contents($fnew);
$im = imagecreatefromstring($img);
$bg = imagecolorat($im, 0, 0);
imagecolorset($im, $bg, 0, 0, 255);
imagepng($im);
imagedestroy($im);
请问大家有好方法吗?谢谢


回复讨论(解决方案)


假如这张图片,我想把后面的各种蓝色背景变成白色,然后上面的苹果图案整体缩小可以缩小网上挪动一下,我可以在最下面加上黑色文字水印,把图案往上挪是因为给水印留位置,别遮挡住这段文字,谢谢。

加水印是可以的

但是去背景都可以的话,拿PS来干什么?

那如果背景是单一颜色呢,是否可以?

bool imagefill ( resource image, int x, int y, int color )


imagefill() 在 image 图像的坐标 x,y(图像左上角为 0, 0)处用 color 颜色执行区域填充(即与 x, y 点颜色相同且相邻的点都会被填充)。


那如果背景是单一颜色呢,是否可以?

function addBg($src,$w,$h)
    {
        $bg = imagecreatetruecolor($w,$h);
        $white = imagecolorallocate($bg,255,255,255);
        imagefill($bg,0,0,$white);//填充背景
 
        //获取目标图片信息
        $info=getimagesize($src);
        $width=$info[0];//目标图片宽度
        $height=$info[1];//目标图片高度
        switch ($info[2]){
            case 1:
                $img = imagecreatefromgif($src);
            break;
            case 2:
                $img = imagecreatefromjpeg($src);
                break;
            case 3:
                $img = imagecreatefrompng($src);
                break;
            default:
                exit('不支持的图像格式');
            break;
        }
        if($height          {
            $x=0;
            $y=($h-$height)/2;//垂直居中
        }
        if($width          {
            $x=($w-$width)/2;//水平居中
            $y=0;
        }
        if($height              $x = ($w-$width)/2;
            $y = ($h-$height)/2;
        }
        imagecopymerge($bg,$img,$x,$y,0,0,$width,$height,100);
        imagejpeg($bg,$src,100);
        imagedestroy($bg);
        imagedestroy($img);
        return $src;
    }
我代入进去没有任何效果啊
addBg("97972188.jpg",$pieces[0],$pieces[1]);

加水印很简单……去背景比较复杂……


加水印我已经实现了,主要是把背景去掉,背景是单一颜色能去掉也行,假如是灰色,变成白色底就行。谢谢各位高手了

我对图像操作不是很熟悉。不过可以给一点我的想法:

如果是单一背景,那么我建议你创建一个透明的png可能更快捷,我记得在创建png时可以指定一个颜色为透明色的。

我找到一段代码,应该感觉比较像,但怎么改还是没有头绪,应该怎么改好呢,请高手指教,谢谢
$o_pic = '97972188.jpg';

//图像中要处理的色阶
$begin_r = 178;
$begin_g = 178;
$begin_b = 178;

list($src_w,$src_h,$src_type) = getimagesize($o_pic);// 获取原图像信息

$file_ext = get_ext($o_pic);//获取扩展名
$target_im = imagecreatetruecolor($src_w,$src_h);//新图


if($file_ext == 'jpg') //转换JPG 开始
{
    $src_im = ImageCreateFromJPEG($o_pic);
    echo $src_w;
    imagecopymerge($target_im,$src_im,0,0,0,0,$src_w,$src_h,100);

    for($x = 0; $x      {
        for($y = 0; $y          {
            $rgb = imagecolorat($src_im, $x, $y);

            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            //将开始设定的色阶值改为白色
            if($r > $begin_r && $g > $begin_g && $b > $begin_b ){   
                imagecolortransparent($target_im, imagecolorallocate($target_im,$r, $g, $b));                
            }
        }
    }

}
header("Content: image/jpeg"); 
imagejpeg($target_im,'c.jpg'); 
imagedestroy($target_im); 

这个方法会不会太慢?我看到是一个像素一个像素循环的。

http://stackoverflow.com/questions/16660729/php-change-background-color-to-transparent

This maybe help. 

Well, it is more or less the same code as you posted. 

有效果,但效果还是不行,毛边太多,图片周围还是有些颜色没有去掉

有些颜色看来是相近的,不是绝对一样,只是一般肉眼无法区别,这样类似的颜色那就不好控制了

有些颜色看来是相近的,不是绝对一样,只是一般肉眼无法区别,这样类似的颜色那就不好控制了

那恐怕是没有办法了,除非你人工修。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools